Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10071950
<NME> .jscsrc <BEF> ADDFILE <MSG> chore(jscsrc): Added .jscsrc <DFF> @@ -0,0 +1,75 @@ +{ + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "case", + "return", + "try", + "catch", + "typeof" + ], + "requireSpaceBeforeBinaryOperators": [ + "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", + "&=", "|=", "^=", "+=", + + "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", + "|", "^", "&&", "||", "===", "==", ">=", + "<=", "<", ">", "!=", "!==" + ], + "requireSpaceBeforeBlockStatements": true, + "requireParenthesesAroundIIFE": true, + "requireSpacesInConditionalExpression": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInFunctionDeclaration": { + "beforeOpeningRoundBrace": true + }, + "requireBlocksOnNewline": 1, + "disallowEmptyBlocks": true, + "disallowSpacesInsideArrayBrackets": true, + "disallowSpacesInsideParentheses": true, + "disallowSpaceAfterObjectKeys": true, + "requireCommaBeforeLineBreak": true, + "disallowSpaceAfterPrefixUnaryOperators": true, + "disallowSpaceBeforePostfixUnaryOperators": true, + "disallowSpaceBeforeBinaryOperators": [ + "," + ], + "requireSpaceBeforeBinaryOperators": true, + "requireSpaceAfterBinaryOperators": true, + "disallowKeywords": [ "with" ], + "disallowMultipleLineBreaks": true, + "validateLineBreaks": "LF", + "validateQuoteMarks": true, + "validateIndentation": 2, + "disallowMixedSpacesAndTabs": true, + "disallowTrailingWhitespace": true, + "disallowTrailingComma": true, + "disallowKeywordsOnNewLine": [ "else" ], + "requireLineFeedAtFileEnd": true, + "requireCapitalizedConstructors": true, + "requireDotNotation": true, + "disallowYodaConditions": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "disallowSpacesInFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpaceAfterObjectKeys": true, + "requireSpaceBeforeObjectValues": true +} \ No newline at end of file
75
chore(jscsrc): Added .jscsrc
0
jscsrc
mit
Semantic-Org/Semantic-UI-Angular
10071951
<NME> .jscsrc <BEF> ADDFILE <MSG> chore(jscsrc): Added .jscsrc <DFF> @@ -0,0 +1,75 @@ +{ + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "case", + "return", + "try", + "catch", + "typeof" + ], + "requireSpaceBeforeBinaryOperators": [ + "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", + "&=", "|=", "^=", "+=", + + "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", + "|", "^", "&&", "||", "===", "==", ">=", + "<=", "<", ">", "!=", "!==" + ], + "requireSpaceBeforeBlockStatements": true, + "requireParenthesesAroundIIFE": true, + "requireSpacesInConditionalExpression": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInFunctionDeclaration": { + "beforeOpeningRoundBrace": true + }, + "requireBlocksOnNewline": 1, + "disallowEmptyBlocks": true, + "disallowSpacesInsideArrayBrackets": true, + "disallowSpacesInsideParentheses": true, + "disallowSpaceAfterObjectKeys": true, + "requireCommaBeforeLineBreak": true, + "disallowSpaceAfterPrefixUnaryOperators": true, + "disallowSpaceBeforePostfixUnaryOperators": true, + "disallowSpaceBeforeBinaryOperators": [ + "," + ], + "requireSpaceBeforeBinaryOperators": true, + "requireSpaceAfterBinaryOperators": true, + "disallowKeywords": [ "with" ], + "disallowMultipleLineBreaks": true, + "validateLineBreaks": "LF", + "validateQuoteMarks": true, + "validateIndentation": 2, + "disallowMixedSpacesAndTabs": true, + "disallowTrailingWhitespace": true, + "disallowTrailingComma": true, + "disallowKeywordsOnNewLine": [ "else" ], + "requireLineFeedAtFileEnd": true, + "requireCapitalizedConstructors": true, + "requireDotNotation": true, + "disallowYodaConditions": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "disallowSpacesInFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpaceAfterObjectKeys": true, + "requireSpaceBeforeObjectValues": true +} \ No newline at end of file
75
chore(jscsrc): Added .jscsrc
0
jscsrc
mit
Semantic-Org/Semantic-UI-Angular
10071952
<NME> helper.rb <BEF> # frozen_string_literal: true module Helper def ab_test(metric_descriptor, control=nil, *alternatives) if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Remove 1.8.7 warning <DFF> @@ -2,9 +2,6 @@ module Split module Helper def ab_test(metric_descriptor, control=nil, *alternatives) - if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? - puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' - end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3'])
0
Remove 1.8.7 warning
3
.rb
rb
mit
splitrb/split
10071953
<NME> helper.rb <BEF> # frozen_string_literal: true module Helper def ab_test(metric_descriptor, control=nil, *alternatives) if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Remove 1.8.7 warning <DFF> @@ -2,9 +2,6 @@ module Split module Helper def ab_test(metric_descriptor, control=nil, *alternatives) - if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? - puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' - end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3'])
0
Remove 1.8.7 warning
3
.rb
rb
mit
splitrb/split
10071954
<NME> helper.rb <BEF> # frozen_string_literal: true module Helper def ab_test(metric_descriptor, control=nil, *alternatives) if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Remove 1.8.7 warning <DFF> @@ -2,9 +2,6 @@ module Split module Helper def ab_test(metric_descriptor, control=nil, *alternatives) - if RUBY_VERSION.match(/1\.8/) && alternatives.length.zero? && ! control.nil? - puts 'WARNING: You should always pass the control alternative through as the second argument with any other alternatives as the third because the order of the hash is not preserved in ruby 1.8' - end # Check if array is passed to ab_test # e.g. ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3'])
0
Remove 1.8.7 warning
3
.rb
rb
mit
splitrb/split
10071955
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end end describe 'conversions' do it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } end it "should be passed to helper block" do expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq({}) end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #88 from philnash/philnash/more-reset-false-issues More issues for finished(:reset => false) <DFF> @@ -177,6 +177,12 @@ describe Split::Helper do session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end + + it 'should not be doing other tests when it has completed one that has :reset => false' do + ab_user[@experiment.key] = @alternative_name + ab_user[@experiment.finished_key] = true + doing_other_tests?(@experiment.key).should be false + end end describe 'conversions' do
6
Merge pull request #88 from philnash/philnash/more-reset-false-issues
0
.rb
rb
mit
splitrb/split
10071956
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end end describe 'conversions' do it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } end it "should be passed to helper block" do expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq({}) end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #88 from philnash/philnash/more-reset-false-issues More issues for finished(:reset => false) <DFF> @@ -177,6 +177,12 @@ describe Split::Helper do session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end + + it 'should not be doing other tests when it has completed one that has :reset => false' do + ab_user[@experiment.key] = @alternative_name + ab_user[@experiment.finished_key] = true + doing_other_tests?(@experiment.key).should be false + end end describe 'conversions' do
6
Merge pull request #88 from philnash/philnash/more-reset-false-issues
0
.rb
rb
mit
splitrb/split
10071957
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end end describe 'conversions' do it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } end it "should be passed to helper block" do expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq({}) end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #88 from philnash/philnash/more-reset-false-issues More issues for finished(:reset => false) <DFF> @@ -177,6 +177,12 @@ describe Split::Helper do session[:split] = nil lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception end + + it 'should not be doing other tests when it has completed one that has :reset => false' do + ab_user[@experiment.key] = @alternative_name + ab_user[@experiment.finished_key] = true + doing_other_tests?(@experiment.key).should be false + end end describe 'conversions' do
6
Merge pull request #88 from philnash/philnash/more-reset-false-issues
0
.rb
rb
mit
splitrb/split
10071958
<NME> utils.ts <BEF> import Scanner from './index'; interface QuotedOptions { /** A character code of quote-escape symbol */ escape?: number; /** Throw error if quotes string can’t be properly consumed */ throws?: boolean; } const defaultQuotedOptions: QuotedOptions = { escape: 92, // \ character throws: false }; /** * Check if given code is a number */ export function isNumber(code: number): boolean { return code > 47 && code < 58; } /** * Check if given character code is alpha code (letter through A to Z) */ export function isAlpha(code: number, from?: number, to?: number): boolean { from = from || 65; // A to = to || 90; // Z code &= ~32; // quick hack to convert any char code to uppercase char code return code >= from && code <= to; } /** * Check if given character code is alpha-numeric (letter through A to Z or number) */ export function isAlphaNumeric(code: number): boolean { return isNumber(code) || isAlpha(code); } export function isAlphaNumericWord(code: number): boolean { return isNumber(code) || isAlphaWord(code); } export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ || code === 160; /* non-breaking space */ } /** * Check if given character code is a space */ export function isSpace(code: number): boolean { return isWhiteSpace(code) || code === 10 /* LF */ || code === 13; /* CR */ } /** * Consumes 'single' or "double"-quoted string from given string, if possible * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); if (stream.eat(isQuote)) { while (!stream.eof()) { switch (stream.next()) { case quote: stream.start = start; return true; case options.escape: stream.next(); break; } } // If we’re here then stream wasn’t properly consumed. // Revert stream and decide what to do stream.pos = start; if (options.throws) { throw stream.error('Unable to consume quoted string'); } } return false; } /** * Check if given character code is a quote character */ export function isQuote(code: number): boolean { return code === 39 /* ' */ || code === 34 /* " */; } /** * Eats paired characters substring, for example `(foo)` or `[bar]` * @param open Character code of pair opening * @param close Character code of pair closing * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; if (stream.eat(open)) { let stack = 1; let ch: number; while (!stream.eof()) { if (eatQuoted(stream, options)) { continue; } ch = stream.next()!; if (ch === open) { stack++; } else if (ch === close) { stack--; if (!stack) { stream.start = start; return true; } } else if (ch === options.escape) { stream.next(); } } // If we’re here then paired character can’t be consumed stream.pos = start; if (options.throws) { throw stream.error(`Unable to find matching pair for ${String.fromCharCode(open)}`); } } return false; } <MSG> New abbreviation tokenizer <DFF> @@ -46,6 +46,10 @@ export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } +/** + * Check if given character code is a white-space character: a space character + * or line breaks + */ export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ @@ -53,7 +57,7 @@ export function isWhiteSpace(code: number) { } /** - * Check if given character code is a space + * Check if given character code is a space character */ export function isSpace(code: number): boolean { return isWhiteSpace(code)
5
New abbreviation tokenizer
1
.ts
ts
mit
emmetio/emmet
10071959
<NME> utils.ts <BEF> import Scanner from './index'; interface QuotedOptions { /** A character code of quote-escape symbol */ escape?: number; /** Throw error if quotes string can’t be properly consumed */ throws?: boolean; } const defaultQuotedOptions: QuotedOptions = { escape: 92, // \ character throws: false }; /** * Check if given code is a number */ export function isNumber(code: number): boolean { return code > 47 && code < 58; } /** * Check if given character code is alpha code (letter through A to Z) */ export function isAlpha(code: number, from?: number, to?: number): boolean { from = from || 65; // A to = to || 90; // Z code &= ~32; // quick hack to convert any char code to uppercase char code return code >= from && code <= to; } /** * Check if given character code is alpha-numeric (letter through A to Z or number) */ export function isAlphaNumeric(code: number): boolean { return isNumber(code) || isAlpha(code); } export function isAlphaNumericWord(code: number): boolean { return isNumber(code) || isAlphaWord(code); } export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ || code === 160; /* non-breaking space */ } /** * Check if given character code is a space */ export function isSpace(code: number): boolean { return isWhiteSpace(code) || code === 10 /* LF */ || code === 13; /* CR */ } /** * Consumes 'single' or "double"-quoted string from given string, if possible * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); if (stream.eat(isQuote)) { while (!stream.eof()) { switch (stream.next()) { case quote: stream.start = start; return true; case options.escape: stream.next(); break; } } // If we’re here then stream wasn’t properly consumed. // Revert stream and decide what to do stream.pos = start; if (options.throws) { throw stream.error('Unable to consume quoted string'); } } return false; } /** * Check if given character code is a quote character */ export function isQuote(code: number): boolean { return code === 39 /* ' */ || code === 34 /* " */; } /** * Eats paired characters substring, for example `(foo)` or `[bar]` * @param open Character code of pair opening * @param close Character code of pair closing * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; if (stream.eat(open)) { let stack = 1; let ch: number; while (!stream.eof()) { if (eatQuoted(stream, options)) { continue; } ch = stream.next()!; if (ch === open) { stack++; } else if (ch === close) { stack--; if (!stack) { stream.start = start; return true; } } else if (ch === options.escape) { stream.next(); } } // If we’re here then paired character can’t be consumed stream.pos = start; if (options.throws) { throw stream.error(`Unable to find matching pair for ${String.fromCharCode(open)}`); } } return false; } <MSG> New abbreviation tokenizer <DFF> @@ -46,6 +46,10 @@ export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } +/** + * Check if given character code is a white-space character: a space character + * or line breaks + */ export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ @@ -53,7 +57,7 @@ export function isWhiteSpace(code: number) { } /** - * Check if given character code is a space + * Check if given character code is a space character */ export function isSpace(code: number): boolean { return isWhiteSpace(code)
5
New abbreviation tokenizer
1
.ts
ts
mit
emmetio/emmet
10071960
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <div class="pagination"> <%= pagination(@experiments) %> </div> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> <MSG> Show percentage improvement of alternatives compared to the control <DFF> @@ -25,8 +25,21 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> + <td> + <%= number_to_percentage(alternative.conversion_rate) %>% + <% if experiment.control.conversion_rate > 0 && !alternative.control? %> + <% if alternative.conversion_rate > experiment.control.conversion_rate %> + <span class='better'> + +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% elsif alternative.conversion_rate < experiment.control.conversion_rate %> + <span class='worse'> + <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% end %> + <% end %> + </td> + <td><%= round(alternative.z_score, 3) %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %>
15
Show percentage improvement of alternatives compared to the control
2
.erb
erb
mit
splitrb/split
10071961
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <div class="pagination"> <%= pagination(@experiments) %> </div> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> <MSG> Show percentage improvement of alternatives compared to the control <DFF> @@ -25,8 +25,21 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> + <td> + <%= number_to_percentage(alternative.conversion_rate) %>% + <% if experiment.control.conversion_rate > 0 && !alternative.control? %> + <% if alternative.conversion_rate > experiment.control.conversion_rate %> + <span class='better'> + +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% elsif alternative.conversion_rate < experiment.control.conversion_rate %> + <span class='worse'> + <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% end %> + <% end %> + </td> + <td><%= round(alternative.z_score, 3) %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %>
15
Show percentage improvement of alternatives compared to the control
2
.erb
erb
mit
splitrb/split
10071962
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <div class="pagination"> <%= pagination(@experiments) %> </div> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> <MSG> Show percentage improvement of alternatives compared to the control <DFF> @@ -25,8 +25,21 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> + <td> + <%= number_to_percentage(alternative.conversion_rate) %>% + <% if experiment.control.conversion_rate > 0 && !alternative.control? %> + <% if alternative.conversion_rate > experiment.control.conversion_rate %> + <span class='better'> + +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% elsif alternative.conversion_rate < experiment.control.conversion_rate %> + <span class='worse'> + <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>% + </span> + <% end %> + <% end %> + </td> + <td><%= round(alternative.z_score, 3) %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %>
15
Show percentage improvement of alternatives compared to the control
2
.erb
erb
mit
splitrb/split
10071963
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "split/trial" describe Split::Trial do let(:user) { mock_user } let(:alternatives) { ["basket", "cart"] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives).save end trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) expect(trial.goals).to eq([]) end describe "alternative" do end describe "alternative" do it "should use the alternative if specified" do alternative = double("alternative", kind_of?: Split::Alternative) trial = Split::Trial.new(experiment: double("experiment"), alternative: alternative, user: user) expect(trial).not_to receive(:choose) expect(trial.alternative).to eq(alternative) end it "should load the alternative when the alternative name is set" do experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"]) experiment.save trial = Split::Trial.new(experiment: experiment, alternative: "basket") expect(trial.alternative.name).to eq("basket") end end describe "metadata" do let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save end it "has metadata on each trial" do trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"], override: "cart") expect(trial.metadata).to eq(metadata["cart"]) end it "has metadata on each trial from the experiment" do trial = Split::Trial.new(experiment: experiment, user: user) trial.choose! expect(trial.metadata).to eq(metadata[trial.alternative.name]) expect(trial.metadata).to match(/#{trial.alternative.name}/) end end describe "#choose!" do let(:context) { double(on_trial_callback: "test callback") } let(:trial) do Split::Trial.new(user: user, experiment: experiment) end shared_examples_for "a trial with callbacks" do it "does not run if on_trial callback is not respondable" do Split.configuration.on_trial = :foo allow(context).to receive(:respond_to?).with(:foo, true).and_return false expect(context).to_not receive(:foo) trial.choose! context end it "runs on_trial callback" do Split.configuration.on_trial = :on_trial_callback expect(context).to receive(:on_trial_callback) trial.choose! context end it "does not run nil on_trial callback" do Split.configuration.on_trial = nil expect(context).not_to receive(:on_trial_callback) trial.choose! context end end def expect_alternative(trial, alternative_name) 3.times do trial.choose! context expect(alternative_name).to include(trial.alternative.name) end end context "when override is present" do let(:override) { "cart" } let(:trial) do Split::Trial.new(user: user, experiment: experiment, override: override) end it_behaves_like "a trial with callbacks" it "picks the override" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, override) end context "when alternative doesn't exist" do let(:override) { nil } it "falls back on next_alternative" do expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when disabled option is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, disabled: true) end it "picks the control", :aggregate_failures do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.on_trial = nil end end context "when Split is globally disabled" do it "picks the control and does not run on_trial callbacks", :aggregate_failures do Split.configuration.enabled = false Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end end context "when experiment has winner" do let(:trial) do Split::Trial.new(user: user, experiment: experiment) end it_behaves_like "a trial with callbacks" it "picks the winner" do experiment.winner = "cart" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "cart") end end context "when exclude is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, exclude: true) end it_behaves_like "a trial with callbacks" it "picks the control" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end end context "when user is already participating" do it_behaves_like "a trial with callbacks" it "picks the same alternative" do user[experiment.key] = "basket" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end context "when alternative is not found" do it "falls back on next_alternative" do user[experiment.key] = "notfound" expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when user is a new participant" do it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do Split.configuration.on_trial_choose = :on_trial_choose_callback expect(experiment).to receive(:next_alternative).and_call_original expect(context).to receive(:on_trial_choose_callback) trial.choose! context expect(trial.alternative.name).to_not be_empty Split.configuration.on_trial_choose = nil end it "assigns user to an alternative" do trial.choose! context expect(alternatives).to include(user[experiment.name]) end context "when cohorting is disabled" do before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) } it "picks the control and does not run on_trial callbacks" do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end it "user is not assigned an alternative" do trial.choose! context expect(user[experiment]).to eq(nil) end end end end describe "#complete!" do context "when there are no goals" do let(:trial) { Split::Trial.new(user: user, experiment: experiment) } it "should complete the trial" do trial.choose! old_completed_count = trial.alternative.completed_count trial.complete! expect(trial.alternative.completed_count).to eq(old_completed_count + 1) end end context "when there are many goals" do let(:goals) { [ "goal1", "goal2" ] } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) } it "increments the completed count corresponding to the goals" do trial.choose! old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h trial.complete! goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) } end end context "when there is 1 goal of type string" do let(:goal) { "goal" } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) } it "increments the completed count corresponding to the goal" do trial.choose! old_completed_count = trial.alternative.completed_count(goal) trial.complete! expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1) end end end describe "alternative recording" do before(:each) { Split.configuration.store_override = false } context "when override is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! expect(trial.alternative.participant_count).to eq(1) end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") expect(user).to_not receive("[]=") trial.choose! end end context "when disabled is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) expect(user).to_not receive("[]=") trial.choose! end end context "when exclude is present" do it "does not store" do trial = Split::Trial.new(user: user, experiment: experiment, exclude: true) expect(user).to_not receive("[]=") trial.choose! end end context "when experiment has winner" do let(:trial) do experiment.winner = "cart" Split::Trial.new(user: user, experiment: experiment) end it "does not store" do expect(user).to_not receive("[]=") trial.choose! end end end end <MSG> Make Trial goals parameter context specific The goals that are being completed are not actually properties of the Trial object and should be used as context for completing a Trial from the helper. <DFF> @@ -13,7 +13,6 @@ describe Split::Trial do trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) - expect(trial.goals).to eq([]) end describe "alternative" do
0
Make Trial goals parameter context specific
1
.rb
rb
mit
splitrb/split
10071964
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "split/trial" describe Split::Trial do let(:user) { mock_user } let(:alternatives) { ["basket", "cart"] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives).save end trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) expect(trial.goals).to eq([]) end describe "alternative" do end describe "alternative" do it "should use the alternative if specified" do alternative = double("alternative", kind_of?: Split::Alternative) trial = Split::Trial.new(experiment: double("experiment"), alternative: alternative, user: user) expect(trial).not_to receive(:choose) expect(trial.alternative).to eq(alternative) end it "should load the alternative when the alternative name is set" do experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"]) experiment.save trial = Split::Trial.new(experiment: experiment, alternative: "basket") expect(trial.alternative.name).to eq("basket") end end describe "metadata" do let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save end it "has metadata on each trial" do trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"], override: "cart") expect(trial.metadata).to eq(metadata["cart"]) end it "has metadata on each trial from the experiment" do trial = Split::Trial.new(experiment: experiment, user: user) trial.choose! expect(trial.metadata).to eq(metadata[trial.alternative.name]) expect(trial.metadata).to match(/#{trial.alternative.name}/) end end describe "#choose!" do let(:context) { double(on_trial_callback: "test callback") } let(:trial) do Split::Trial.new(user: user, experiment: experiment) end shared_examples_for "a trial with callbacks" do it "does not run if on_trial callback is not respondable" do Split.configuration.on_trial = :foo allow(context).to receive(:respond_to?).with(:foo, true).and_return false expect(context).to_not receive(:foo) trial.choose! context end it "runs on_trial callback" do Split.configuration.on_trial = :on_trial_callback expect(context).to receive(:on_trial_callback) trial.choose! context end it "does not run nil on_trial callback" do Split.configuration.on_trial = nil expect(context).not_to receive(:on_trial_callback) trial.choose! context end end def expect_alternative(trial, alternative_name) 3.times do trial.choose! context expect(alternative_name).to include(trial.alternative.name) end end context "when override is present" do let(:override) { "cart" } let(:trial) do Split::Trial.new(user: user, experiment: experiment, override: override) end it_behaves_like "a trial with callbacks" it "picks the override" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, override) end context "when alternative doesn't exist" do let(:override) { nil } it "falls back on next_alternative" do expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when disabled option is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, disabled: true) end it "picks the control", :aggregate_failures do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.on_trial = nil end end context "when Split is globally disabled" do it "picks the control and does not run on_trial callbacks", :aggregate_failures do Split.configuration.enabled = false Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end end context "when experiment has winner" do let(:trial) do Split::Trial.new(user: user, experiment: experiment) end it_behaves_like "a trial with callbacks" it "picks the winner" do experiment.winner = "cart" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "cart") end end context "when exclude is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, exclude: true) end it_behaves_like "a trial with callbacks" it "picks the control" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end end context "when user is already participating" do it_behaves_like "a trial with callbacks" it "picks the same alternative" do user[experiment.key] = "basket" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end context "when alternative is not found" do it "falls back on next_alternative" do user[experiment.key] = "notfound" expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when user is a new participant" do it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do Split.configuration.on_trial_choose = :on_trial_choose_callback expect(experiment).to receive(:next_alternative).and_call_original expect(context).to receive(:on_trial_choose_callback) trial.choose! context expect(trial.alternative.name).to_not be_empty Split.configuration.on_trial_choose = nil end it "assigns user to an alternative" do trial.choose! context expect(alternatives).to include(user[experiment.name]) end context "when cohorting is disabled" do before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) } it "picks the control and does not run on_trial callbacks" do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end it "user is not assigned an alternative" do trial.choose! context expect(user[experiment]).to eq(nil) end end end end describe "#complete!" do context "when there are no goals" do let(:trial) { Split::Trial.new(user: user, experiment: experiment) } it "should complete the trial" do trial.choose! old_completed_count = trial.alternative.completed_count trial.complete! expect(trial.alternative.completed_count).to eq(old_completed_count + 1) end end context "when there are many goals" do let(:goals) { [ "goal1", "goal2" ] } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) } it "increments the completed count corresponding to the goals" do trial.choose! old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h trial.complete! goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) } end end context "when there is 1 goal of type string" do let(:goal) { "goal" } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) } it "increments the completed count corresponding to the goal" do trial.choose! old_completed_count = trial.alternative.completed_count(goal) trial.complete! expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1) end end end describe "alternative recording" do before(:each) { Split.configuration.store_override = false } context "when override is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! expect(trial.alternative.participant_count).to eq(1) end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") expect(user).to_not receive("[]=") trial.choose! end end context "when disabled is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) expect(user).to_not receive("[]=") trial.choose! end end context "when exclude is present" do it "does not store" do trial = Split::Trial.new(user: user, experiment: experiment, exclude: true) expect(user).to_not receive("[]=") trial.choose! end end context "when experiment has winner" do let(:trial) do experiment.winner = "cart" Split::Trial.new(user: user, experiment: experiment) end it "does not store" do expect(user).to_not receive("[]=") trial.choose! end end end end <MSG> Make Trial goals parameter context specific The goals that are being completed are not actually properties of the Trial object and should be used as context for completing a Trial from the helper. <DFF> @@ -13,7 +13,6 @@ describe Split::Trial do trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) - expect(trial.goals).to eq([]) end describe "alternative" do
0
Make Trial goals parameter context specific
1
.rb
rb
mit
splitrb/split
10071965
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "split/trial" describe Split::Trial do let(:user) { mock_user } let(:alternatives) { ["basket", "cart"] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives).save end trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) expect(trial.goals).to eq([]) end describe "alternative" do end describe "alternative" do it "should use the alternative if specified" do alternative = double("alternative", kind_of?: Split::Alternative) trial = Split::Trial.new(experiment: double("experiment"), alternative: alternative, user: user) expect(trial).not_to receive(:choose) expect(trial.alternative).to eq(alternative) end it "should load the alternative when the alternative name is set" do experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"]) experiment.save trial = Split::Trial.new(experiment: experiment, alternative: "basket") expect(trial.alternative.name).to eq("basket") end end describe "metadata" do let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] } let(:experiment) do Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save end it "has metadata on each trial" do trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"], override: "cart") expect(trial.metadata).to eq(metadata["cart"]) end it "has metadata on each trial from the experiment" do trial = Split::Trial.new(experiment: experiment, user: user) trial.choose! expect(trial.metadata).to eq(metadata[trial.alternative.name]) expect(trial.metadata).to match(/#{trial.alternative.name}/) end end describe "#choose!" do let(:context) { double(on_trial_callback: "test callback") } let(:trial) do Split::Trial.new(user: user, experiment: experiment) end shared_examples_for "a trial with callbacks" do it "does not run if on_trial callback is not respondable" do Split.configuration.on_trial = :foo allow(context).to receive(:respond_to?).with(:foo, true).and_return false expect(context).to_not receive(:foo) trial.choose! context end it "runs on_trial callback" do Split.configuration.on_trial = :on_trial_callback expect(context).to receive(:on_trial_callback) trial.choose! context end it "does not run nil on_trial callback" do Split.configuration.on_trial = nil expect(context).not_to receive(:on_trial_callback) trial.choose! context end end def expect_alternative(trial, alternative_name) 3.times do trial.choose! context expect(alternative_name).to include(trial.alternative.name) end end context "when override is present" do let(:override) { "cart" } let(:trial) do Split::Trial.new(user: user, experiment: experiment, override: override) end it_behaves_like "a trial with callbacks" it "picks the override" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, override) end context "when alternative doesn't exist" do let(:override) { nil } it "falls back on next_alternative" do expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when disabled option is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, disabled: true) end it "picks the control", :aggregate_failures do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.on_trial = nil end end context "when Split is globally disabled" do it "picks the control and does not run on_trial callbacks", :aggregate_failures do Split.configuration.enabled = false Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end end context "when experiment has winner" do let(:trial) do Split::Trial.new(user: user, experiment: experiment) end it_behaves_like "a trial with callbacks" it "picks the winner" do experiment.winner = "cart" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "cart") end end context "when exclude is true" do let(:trial) do Split::Trial.new(user: user, experiment: experiment, exclude: true) end it_behaves_like "a trial with callbacks" it "picks the control" do expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end end context "when user is already participating" do it_behaves_like "a trial with callbacks" it "picks the same alternative" do user[experiment.key] = "basket" expect(experiment).to_not receive(:next_alternative) expect_alternative(trial, "basket") end context "when alternative is not found" do it "falls back on next_alternative" do user[experiment.key] = "notfound" expect(experiment).to receive(:next_alternative).and_call_original expect_alternative(trial, alternatives) end end end context "when user is a new participant" do it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do Split.configuration.on_trial_choose = :on_trial_choose_callback expect(experiment).to receive(:next_alternative).and_call_original expect(context).to receive(:on_trial_choose_callback) trial.choose! context expect(trial.alternative.name).to_not be_empty Split.configuration.on_trial_choose = nil end it "assigns user to an alternative" do trial.choose! context expect(alternatives).to include(user[experiment.name]) end context "when cohorting is disabled" do before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) } it "picks the control and does not run on_trial callbacks" do Split.configuration.on_trial = :on_trial_callback expect(experiment).to_not receive(:next_alternative) expect(context).not_to receive(:on_trial_callback) expect_alternative(trial, "basket") Split.configuration.enabled = true Split.configuration.on_trial = nil end it "user is not assigned an alternative" do trial.choose! context expect(user[experiment]).to eq(nil) end end end end describe "#complete!" do context "when there are no goals" do let(:trial) { Split::Trial.new(user: user, experiment: experiment) } it "should complete the trial" do trial.choose! old_completed_count = trial.alternative.completed_count trial.complete! expect(trial.alternative.completed_count).to eq(old_completed_count + 1) end end context "when there are many goals" do let(:goals) { [ "goal1", "goal2" ] } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) } it "increments the completed count corresponding to the goals" do trial.choose! old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h trial.complete! goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) } end end context "when there is 1 goal of type string" do let(:goal) { "goal" } let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) } it "increments the completed count corresponding to the goal" do trial.choose! old_completed_count = trial.alternative.completed_count(goal) trial.complete! expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1) end end end describe "alternative recording" do before(:each) { Split.configuration.store_override = false } context "when override is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! expect(trial.alternative.participant_count).to eq(1) end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, override: "basket") expect(user).to_not receive("[]=") trial.choose! end end context "when disabled is present" do it "stores when store_override is true" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) Split.configuration.store_override = true expect(user).to receive("[]=") trial.choose! end it "does not store when store_override is false" do trial = Split::Trial.new(user: user, experiment: experiment, disabled: true) expect(user).to_not receive("[]=") trial.choose! end end context "when exclude is present" do it "does not store" do trial = Split::Trial.new(user: user, experiment: experiment, exclude: true) expect(user).to_not receive("[]=") trial.choose! end end context "when experiment has winner" do let(:trial) do experiment.winner = "cart" Split::Trial.new(user: user, experiment: experiment) end it "does not store" do expect(user).to_not receive("[]=") trial.choose! end end end end <MSG> Make Trial goals parameter context specific The goals that are being completed are not actually properties of the Trial object and should be used as context for completing a Trial from the helper. <DFF> @@ -13,7 +13,6 @@ describe Split::Trial do trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) expect(trial.experiment).to eq(experiment) expect(trial.alternative).to eq(alternative) - expect(trial.goals).to eq([]) end describe "alternative" do
0
Make Trial goals parameter context specific
1
.rb
rb
mit
splitrb/split
10071966
<NME> metric_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do experiment = Split::Experiment.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment1, experiment2]) end it "should load both the metric experiments and an experiment with the same name" do experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment2]) metric.save expect(Split::Metric.possible_experiments("purchase")).to include(experiment1, experiment2) end end end <MSG> Remove unnecessary duplicate methods <DFF> @@ -4,13 +4,13 @@ require 'split/metric' describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do - experiment = Split::Experiment.find_or_create('color', 'red', 'blue') + experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do - experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save @@ -18,8 +18,8 @@ describe Split::Metric do end it "should load both the metric experiments and an experiment with the same name" do - experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('purchase', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save
5
Remove unnecessary duplicate methods
5
.rb
rb
mit
splitrb/split
10071967
<NME> metric_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do experiment = Split::Experiment.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment1, experiment2]) end it "should load both the metric experiments and an experiment with the same name" do experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment2]) metric.save expect(Split::Metric.possible_experiments("purchase")).to include(experiment1, experiment2) end end end <MSG> Remove unnecessary duplicate methods <DFF> @@ -4,13 +4,13 @@ require 'split/metric' describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do - experiment = Split::Experiment.find_or_create('color', 'red', 'blue') + experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do - experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save @@ -18,8 +18,8 @@ describe Split::Metric do end it "should load both the metric experiments and an experiment with the same name" do - experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('purchase', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save
5
Remove unnecessary duplicate methods
5
.rb
rb
mit
splitrb/split
10071968
<NME> metric_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do experiment = Split::Experiment.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment1, experiment2]) end it "should load both the metric experiments and an experiment with the same name" do experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save metric = Split::Metric.new(name: "purchase", experiments: [experiment2]) metric.save expect(Split::Metric.possible_experiments("purchase")).to include(experiment1, experiment2) end end end <MSG> Remove unnecessary duplicate methods <DFF> @@ -4,13 +4,13 @@ require 'split/metric' describe Split::Metric do describe 'possible experiments' do it "should load the experiment if there is one, but no metric" do - experiment = Split::Experiment.find_or_create('color', 'red', 'blue') + experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') expect(Split::Metric.possible_experiments('color')).to eq([experiment]) end it "should load the experiments in a metric" do - experiment1 = Split::Experiment.find_or_create('color', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment1, experiment2]) metric.save @@ -18,8 +18,8 @@ describe Split::Metric do end it "should load both the metric experiments and an experiment with the same name" do - experiment1 = Split::Experiment.find_or_create('purchase', 'red', 'blue') - experiment2 = Split::Experiment.find_or_create('size', 'big', 'small') + experiment1 = Split::ExperimentCatalog.find_or_create('purchase', 'red', 'blue') + experiment2 = Split::ExperimentCatalog.find_or_create('size', 'big', 'small') metric = Split::Metric.new(:name => 'purchase', :experiments => [experiment2]) metric.save
5
Remove unnecessary duplicate methods
5
.rb
rb
mit
splitrb/split
10071969
<NME> README.md <BEF> # transducers.js A small library for generalized transformation of data. This provides a bunch of transformation functions that can be applied to any data structure. It is a direct port of Clojure's [transducers](http://blog.cognitect.com/blog/2014/8/6/transducers-are-coming) in JavaScript. Read more in [this post](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data). The algorithm behind this, explained in the above post, not only allows for it to work with any data structure (arrays, objects, iterators, immutable data structures, you name it) but it also provides better performance than other alternatives such as underscore or lodash. This is because there are no intermediate collections. See [this post](http://jlongster.com/Transducers.js-Round-2-with-Benchmarks) for benchmarks. ``` npm install transducers.js ``` For browsers, grab the file `dist/transducers.js`. When writing programs, we frequently write methods that take in collections, do something with them, and return a result. The problem is that we frequently only write these functions to work a specific data structure, so if we ever change our data type or wanted to reuse that functionality, you can't. We need to decouple these kinds of concerns. A transducer is a function that takes a reducing function and returns a new one. It can perform the necessary work and call the original reducing function to move on to the next "step". In this library, a transducer a little more than that (it's actually an object that also supports init and finalizer methods) but generally you don't have to worry about these internal details. Read [my post](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data) if you want to learn more about the algorithm. ```js var transform = compose( map(x => x * 3), filter(x => x % 2 === 0), take(2) ); seq([1, 2, 3, 4, 5], transform); // -> [ 6, 12 ] function* nums() { var i = 1; while(true) { yield i++; } } into([], transform, nums()); // -> [ 6, 12 ] into([], transform, Immutable.List.of(1, 2, 3, 4, 5)) // -> [ 6, 12 ] ``` All of these work with arrays, objects, and any iterable data structure (like [immutable-js](https://github.com/facebook/immutable-js)) and you get all the high performance guarantees for free. The above code always only performs 2 transformations because of `take(2)`, no matter how large the array. This is done without laziness or any overhead of intermediate structures. ## Transformations The following transformations are available, and there are more to come (like `partition`). * `map(coll?, f, ctx?)` &mdash; call `f` on each item * `filter(coll?, f, ctx?)` &mdash; only include the items where the result of calling `f` with the item is truthy * `remove(coll?, f, ctx?)` &mdash; only include the items where the result of calling `f` with the item is falsy * `keep(coll?)` &mdash; remove all items that are `null` or `undefined` * `take(coll?, n)` &mdash; grab only the first `n` items * `takeWhile(coll?, f, ctx?)` &mdash; grab only the first items where the result of calling `f` with the item is truthy * `drop(coll?, n)` &mdash; drop the first `n` items and only include the rest * `dropWhile(coll?, f, ctx?)` &mdash; drop the first items where the result of calling `f` with the item is truthy * `dedupe(coll?)` &mdash; remove consecutive duplicates (equality compared with ===) The above functions optionally take a collection to immediately perform the transformation on, and a context to bind `this` to when calling `f`. That means you can call them in four ways: * Immediately perform a map: `map([1, 2, 3], x => x + 1)` * Same as above but call the function with `this` as `ctx`: `map([1, 2, 3], function(x) { return x + 1; }, ctx)` * Make a map transducer: `map(x => x + 1)` * Same as above but with `this` as `ctx`: `map(function(x) { return x + 1; }, ctx)` (I will be using the ES6 fat arrow syntax, but if that's not available just `function` instead) The signature of running an immediate map is the same familiar one as seen in lodash and underscore, but now you can drop the collection to make a transducer and run multiple transformations with good performance: ```js var transform = compose( map(x => x + 1), filter(x => x % 2 === 0), take(2) ); ``` `compose` is a provided function that simply turns `compose(f, g)` into `x => f(g(x))`. You use it to build up transformations. The above transformation would always run the map and filter **only twice** because only two items are needed, and it short-circuits once it gets two items. Again, this is done without laziness, read more [here](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data). There are also 2 transducers available for taking collections and "catting" them into the transformation stream: * `cat` &mdash; take collections and forward each item individually, essentially flattening it * `mapcat(f)` &mdash; same as `cat`, but first apply `f` to each collection Just pass `cat` straight through like so: `compose(filter(x => x.length < 10), cat)`. That would take all arrays with a length less than 10 and flatten them out into a single array. ## Applying Transformations Building data structure-agnostic transformations is cool, but how do you actually use them? `transducers.js` provides several integration points. To use a transformation, we need to know how to iterate over the source data structure and how to build up a new one. The former is easy; we can work with arrays, objects, and anything can uses the ES6 iterator protocol (Maps, Sets, generators, etc). All the the below functions works with them. For the latter, you need to specify what you want back. The following functions allow you to make a new data structure and possibly apply a transformation: * `toArray(coll, xform?)` &mdash; Turn `coll` into an array, applying the transformation `xform` to each item if provided. The transform is optional in case you want to do something like turn an iterator into an array. * `toObj(coll, xform?)` &mdash; Turn `coll` into an object if possible, applying the transformation `xform` if provided. When an object is iterated it produces two-element arrays `[key, value]`, and `obj` will turn these back into an object. * `toIter(coll, xform?)` &mdash; Make an iterator over `coll`, and apply the transformation `xform` to each value if specified. Note that `coll` can just be another iterator. **Transformations will be applied lazily**. * `seq(coll, xform)` &mdash; A generalized method that will return the same data type that was passed in as `coll`, with `xform` applied. You will usually use this unless you know you want an array, object, or iterator. If `coll` is an iterator, another iterator will be returned and transformations will be applied lazily. * `into(to, xform, from)` &mdash; Apply `xform` to each item in `from` and append it to `to`. This has the effect of "pouring" elements into `to`. You will commonly use this when converting one type of object to another. * `transduce(coll, xform, reducer, init?)` &mdash; Like `reduce`, but apply `xform` to each value before passing to `reducer`. If `init` is not specify it will attempt to get it from `reducer`. The possibilities are endless: ```js // Map an object seq({ foo: 1, bar: 2 }, map(kv => [kv[0], kv[1] + 1])); // -> { foo: 2, bar: 3 } // Make an array from an object toArray({ foo: 1, bar: 2 }); // -> [ [ 'foo', 1 ], [ 'bar', 2 ] ] // Make an array from an iterable function* nums() { var i = 1; while(true) { yield i++; } } iter.next().value; // -> 8 iter.next().value; // -> 10 ``` ## Laziness Transducers remove the requirement of being lazy to optimize for things like `take(10)`. However, it can still be useful to "bind" a collection to a set of transformations and pass it around, without actually evaluating the transformations. As noted above, whenever you apply transformations to an iterator it does so lazily. It's easy convert array transformations into a lazy operation, just use the utility function `iterator` to grab an iterator of the array instead: ```js seq(iterator([1, 2, 3]), compose( map(x => x + 1), filter(x => x % 2 === 0))) // -> <Iterator> ``` Our transformations are completely blind to the fact that our transformations may or may not be lazy. ## Utility Functions This library provides a few small utility functions: * `iterator(coll)` &mdash; Get an iterator for `coll`, which can be any type like array, object, iterator, or custom data type * `push(arr, value)` &mdash; Push `value` onto `arr` and return `arr` * `merge(obj, value)` &mdash; Merge `value` into `obj`. `value` can be another object or a two-element array of `[key, value]` * `range(n)` &mdash; Make an array of size `n` filled with numbers from `0..n`. ## immutable-js We've talked about how this can be applied to any data structure &mdash; let's see that in action. Here's how you could use this with [immutable-js](https://github.com/facebook/immutable-js). ```js Immutable.fromJS( seq(Immutable.Vector(1, 2, 3, 4, 5), compose( map(function(x) { return x + 10; }), map(function(x) { return x * 2; }), filter(function(x) { return x % 5 === 0; }), filter(function(x) { return x % 2 === 0; }))) ) ``` We can use our familiar `seq` function because `Immutable.Vector` implements the iterator protocol, so we can iterator over it. Because `seq` is working with an iterator, it returns a new iterator that will *lazily transform each value*. We can simply pass this iterator into `Immutable.Vector.from` to construct a new one, and we have a new transformed immutable vector with no intermediate collections except for one lazy transformer! The builtin transformations perform well because they minimize allocations, but since we don't have any intermediate structures or laziness machinery, this performs slightly better. The point is not to beat it, but to show that both are high-performance but we can apply our performance to any data structure. ## CSP Channels This not only works with all the JavaScript data structures you can think of, but it even works for things like streams. Soon channels from [js-csp](https://github.com/ubolonton/js-csp) will be able to take a transformation and you get all of this for channels for free: ```js var ch = chan(1, compose( cat, map(x => x + 1), dedupe(), drop(3) )); ``` ## The `transducer` protocol While it's great that you can apply transducers to custom data structures, it's a bit annoying to always have to use constructor functions like `Immutable.fromJS`. One option is to define a new protocol complementary to `iterator`. This conforms to the [official transducer spec](https://github.com/cognitect-labs/transducers-js/issues/20) so if you implement this, you can use it with all transducer libraries that conform to it. To implement the transducer protocol, you add methods to the prototype of your data structure. A transformer is an object with three methods: `init`, `result`, and `step`. `init` returns a new empty object, `result`, can perform any finalization steps on the resulting collection, and `step` performs a reduce. These methods are namespaced and in the future could be symbols. Here's what it looks like for `Immutable.List`: ```js Immutable.List.prototype['@@transducer/init'] = function() { return Immutable.List().asMutable(); }; Immutable.List.prototype['@@transducer/result'] = function(lst) { return lst.asImmutable(); }; Immutable.List.prototype['@@transducer/step'] = function(lst, x) { return lst.push(x); }; ``` If you implement the transducer protocol, now your data structure will work with *all* of the builtin functions. You can just use `seq` like normal and you get back an immutable vector! ```js t.seq(Immutable.List.of(1, 2, 3, 4, 5), t.compose( t.map(function(x) { return x + 10; }), t.map(function(x) { return x * 2; }), t.filter(function(x) { return x % 5 === 0; }), t.filter(function(x) { return x % 2 === 0; }))); // -> List [ 30 ] ``` ## Running Tests ``` npm install gulp mocha build/tests ``` [BSD LICENSE](https://github.com/jlongster/transducers.js/blob/master/LICENSE) <MSG> readme typo <DFF> @@ -119,7 +119,7 @@ If you are authoring a new data structure, you could provide functions for runni * `@@append` - add a new item to the collection * `@@empty` - return a newly-allocated empty collection of the same type -With these two methods, we can build up new collections arbitrarily without caring our their actual implementation. They are prefixed with two `at`s because ideally they are ES6 symbols, and that's how we write them in docs. Since symbols aren't implemented everywhere yet, you can just add methods literally called `"@@append"`. +With these two methods, we can build up new collections arbitrarily without caring about their actual implementation. They are prefixed with two `at`s because ideally they are ES6 symbols, and that's how we write them in docs. Since symbols aren't implemented everywhere yet, you can just add methods literally called `"@@append"`. With JavaScript prototypes, you can actually monkeypatch existing libraries quite easily. Let's say we wanted to use [immutable-js](https://github.com/facebook/immutable-js). It already implement the iterator protocol with a method `@@iterator`, but let's add two more:
1
readme typo
1
.md
md
bsd-2-clause
jlongster/transducers.js
10071970
<NME> settings.py <BEF> from conf.default import * import os DEBUG = True TEMPLATE_DEBUG = DEBUG LOCAL_DEVELOPMENT = True if LOCAL_DEVELOPMENT: import sys sys.path.append(os.path.dirname(__file__)) ADMINS = ( DJANGOPYPI_ALLOW_VERSION_OVERWRITE = False DJANGOPYPI_RELEASE_UPLOAD_TO = 'dists' MANAGERS = ADMINS DATABASE_ENGINE = '' DATABASE_HOST = '' DATABASE_PORT = '' 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.markup', 'djangopypi', ) <MSG> bugfix: added django.contrib.admindocs as needed APP (it is referenced at urls.py) <DFF> @@ -13,6 +13,9 @@ ADMINS = ( DJANGOPYPI_ALLOW_VERSION_OVERWRITE = False DJANGOPYPI_RELEASE_UPLOAD_TO = 'dists' +# change to False if you do not want Django's default server to serve static pages +LOCAL_DEVELOPMENT = True + MANAGERS = ADMINS DATABASE_ENGINE = '' @@ -88,5 +91,6 @@ INSTALLED_APPS = ( 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.markup', + 'django.contrib.admindocs', 'djangopypi', )
4
bugfix: added django.contrib.admindocs as needed APP (it is referenced at urls.py)
0
.py
py
bsd-3-clause
ask/chishop
10071971
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](https://www.codetriage.com/splitrb/split) > 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app. Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis. Split is designed to be hacker friendly, allowing for maximum customisation and extensibility. ## Install ### Requirements Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2. If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3) Split uses Redis as a datastore. Split only supports Redis 4.0 or greater. If you're on OS X, Homebrew is the simplest way to install Redis: ```bash brew install redis redis-server /usr/local/etc/redis.conf ``` You now have a Redis daemon running on port `6379`. ### Setup ```bash gem install split ``` #### Rails Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'. #### Sinatra To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app: ```ruby require 'split' class MySinatraApp < Sinatra::Base enable :sessions helpers Split::Helper get '/' do ... end ``` ## Usage To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments. `ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on. It can be used to render different templates, show different text or any other case based logic. `ab_finished` is used to make a completion of an experiment, or conversion. Example: View ```erb <% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %> <%= image_tag(button_file, alt: "Login!") %> <% end %> ``` Example: Controller ```ruby def register_new_user # See what level of free points maximizes users' decision to buy replacement points. @starter_points = ab_test(:new_user_free_points, '100', '200', '300') end ``` Example: Conversion tracking (in a controller!) ```ruby def buy_new_points # some business logic ab_finished(:new_user_free_points) end ``` Example: Conversion tracking (in a view) ```erb Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %> ``` You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki). ## Statistical Validity Split has two options for you to use to determine which alternative is the best. The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch. As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none). [Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience. The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test. Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day). ```ruby Split.configure do |config| config.winning_alternative_recalculation_interval = 3600 # 1 hour end ``` ## Extras ### Weighted alternatives Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested. To do this you can pass a weight with each alternative in the following ways: ```ruby ab_test(:homepage_design, {'Old' => 18}, {'New' => 2}) ab_test(:homepage_design, 'Old', {'New' => 1.0/9}) ab_test(:homepage_design, {'Old' => 9}, 'New') ``` This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1. ### Overriding alternatives For development and testing, you may wish to force your app to always return an alternative. You can do this by passing it as a parameter in the url. If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as: http://myawesomesite.com?ab_test[button_color]=red will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option. In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter. http://myawesomesite.com?SPLIT_DISABLE=true It is not required to send `SPLIT_DISABLE=false` to activate Split. ### Rspec Helper To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below: ```ruby # Create a file with these contents at 'spec/support/split_helper.rb' # and ensure it is `require`d in your rails_helper.rb or spec_helper.rb module SplitHelper # Force a specific experiment alternative to always be returned: # use_ab_test(signup_form: "single_page") # # Force alternatives for multiple experiments: # use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices") # def use_ab_test(alternatives_by_experiment) allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block| variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } block.call(variant) unless block.nil? variant end end end # Make the `use_ab_test` method available to all specs: RSpec.configure do |config| config.include SplitHelper end ``` Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example: ```ruby it "registers using experimental signup" do use_ab_test experiment_name: "alternative_name" post "/signups" ... end ``` ### Starting experiments manually By default new A/B tests will be active right after deployment. In case you would like to start new test a while after the deploy, you can do it by setting the `start_manually` configuration option to `true`. After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized. ### Reset after completion When a user completes a test their session is reset so that they may start the test again in the future. To stop this behaviour you can pass the following option to the `ab_finished` method: ```ruby ab_finished(:experiment_name, reset: false) ``` The user will then always see the alternative they started with. Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`. ### Reset experiments manually By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`. You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything. ### Multiple experiments at once By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests. To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = true end ``` This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another. To address this, setting the `allow_multiple_experiments` config option to 'control' like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = 'control' end ``` For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment. ### Experiment Persistence Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment. By default Split will store the tests for each user in the session. You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing. #### Cookies ```ruby Split.configure do |config| config.persistence = :cookie end ``` When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds). ```ruby Split.configure do |config| config.persistence = :cookie config.persistence_cookie_length = 2592000 # 30 days end ``` The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" } __Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API #### Redis Using Redis will allow ab_users to persist across sessions or machines. ```ruby Split.configure do |config| config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id }) # Equivalent # config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id) end ``` Options: * `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration) * `namespace`: separate namespace to store these persisted values (default "persistence") * `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments) #### Dual Adapter The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users. ```ruby cookie_adapter = Split::Persistence::CookieAdapter redis_adapter = Split::Persistence::RedisAdapter.with_config( lookup_by: -> (context) { context.send(:current_user).try(:id) }, expire_seconds: 2592000) Split.configure do |config| config.persistence = Split::Persistence::DualAdapter.with_config( logged_in: -> (context) { !context.send(:current_user).try(:id).nil? }, logged_in_adapter: redis_adapter, logged_out_adapter: cookie_adapter) config.persistence_cookie_length = 2592000 # 30 days end ``` #### Custom Adapter Your custom adapter needs to implement the same API as existing adapters. See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point. ```ruby Split.configure do |config| config.persistence = YourCustomAdapterClass end ``` ### Trial Event Hooks You can define methods that will be called at the same time as experiment alternative participation and goal completion. For example: ``` ruby Split.configure do |config| config.on_trial = :log_trial # run on every trial config.on_trial_choose = :log_trial_choose # run on trials with new users only config.on_trial_complete = :log_trial_complete end ``` Set these attributes to a method name available in the same context as the `ab_test` method. These methods should accept one argument, a `Trial` instance. ``` ruby def log_trial(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_choose(trial) logger.info "[new user] experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_complete(trial) logger.info "experiment=%s alternative=%s user=%s complete=true" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` #### Views If you are running `ab_test` from a view, you must define your event hook callback as a [helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method) in the controller: ``` ruby helper_method :log_trial_choose def log_trial_choose(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` ### Experiment Hooks You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split. For example: ``` ruby Split.configure do |config| # after experiment reset or deleted config.on_experiment_reset = -> (example) { # Do something on reset } config.on_experiment_delete = -> (experiment) { # Do something else on delete } # before experiment reset or deleted config.on_before_experiment_reset = -> (example) { # Do something on reset } config.on_before_experiment_delete = -> (experiment) { # Do something else on delete } # after experiment winner had been set config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose } end ``` ## Web Interface Split comes with a Sinatra-based front end to get an overview of how your experiments are doing. If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru` ```ruby require 'split/dashboard' run Rack::URLMap.new \ "/" => Your::App.new, "/split" => Split::Dashboard.new ``` However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile: ```ruby gem 'split', require: 'split/dashboard' ``` Then adding this to config/routes.rb ```ruby mount Split::Dashboard, at: 'split' ``` You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file) ```ruby # Rails apps or apps that already depend on activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end # Apps without activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end ``` You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following: ```ruby match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do request.env['warden'].authenticated? # are we authenticated? request.env['warden'].authenticate! # authenticate if not already # or even check any other condition such as request.env['warden'].user.is_admin? end ``` More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/) ### Screenshot ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## Configuration You can override the default configuration options of Split like so: ```ruby Split.configure do |config| config.db_failover = true # handle Redis errors gracefully config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) } config.allow_multiple_experiments = true config.enabled = true config.persistence = Split::Persistence::SessionAdapter #config.start_manually = false ## new test will have to be started manually from the admin panel. default false #config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes config.include_rails_helper = true config.redis = "redis://custom.redis.url:6380" end ``` Split looks for the Redis host in the environment variable `REDIS_URL` then defaults to `redis://localhost:6379` if not specified by configure block. On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to determine which env variable key to use when retrieving the host config. This defaults to `REDIS_URL`. ### Filtering In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users. Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic. ```ruby Split.configure do |config| # bot config config.robot_regex = /my_custom_robot_regex/ # or config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion" # IP config config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/ # or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? } config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) } end ``` ### Experiment configuration Instead of providing the experiment options inline, you can store them in a hash. This hash can control your experiment's alternatives, weights, algorithm and if the experiment resets once finished: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], resettable: false }, :my_second_experiment => { algorithm: 'Split::Algorithms::Whiplash', alternatives: [ { name: "a", percent: 67 }, { name: "b", percent: 33 } ] } } end ``` You can also store your experiments in a YAML file: ```ruby Split.configure do |config| config.experiments = YAML.load_file "config/experiments.yml" end ``` You can then define the YAML file like: ```yaml my_first_experiment: alternatives: - a - b my_second_experiment: alternatives: - name: a percent: 67 - name: b percent: 33 resettable: false ``` This simplifies the calls from your code: ```ruby ab_test(:my_first_experiment) ``` and: ```ruby ab_finished(:my_first_experiment) ``` You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"} } } } end ``` ```yaml my_first_experiment: alternatives: - a - b metadata: a: text: "Have a fantastic day" b: text: "Don't get hit by a bus" ``` This allows for some advanced experiment configuration using methods like: ```ruby trial.alternative.name # => "a" trial.metadata['text'] # => "Have a fantastic day" ``` or in views: ```erb <% ab_test("my_first_experiment") do |alternative, meta| %> <%= alternative %> <small><%= meta['text'] %></small> <% end %> ``` The keys used in meta data should be Strings #### Metrics You might wish to track generic metrics, such as conversions, and use those to complete multiple different experiments without adding more to your code. You can use the configuration hash to do this, thanks to the `:metric` option. ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metric: :my_metric } } end ``` Your code may then track a completion using the metric instead of the experiment name: ```ruby ab_finished(:my_metric) ``` You can also create a new metric by instantiating and saving a new Metric object. ```ruby Split::Metric.new(:my_metric) Split::Metric.save ``` #### Goals You might wish to allow an experiment to have multiple, distinguishable goals. The API to define goals for an experiment is this: ```ruby ab_test({link_color: ["purchase", "refund"]}, "red", "blue") ``` or you can define them in a configuration file: ```ruby Split.configure do |config| config.experiments = { link_color: { alternatives: ["red", "blue"], goals: ["purchase", "refund"] } } end ``` To complete a goal conversion, you do it like: ```ruby ab_finished(link_color: "purchase") ``` Note that if you pass additional options, that should be a separate hash: ```ruby ab_finished({ link_color: "purchase" }, reset: false) ``` **NOTE:** This does not mean that a single experiment can complete more than one goal. Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.) **Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion"). **Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK. **Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK. #### Combined Experiments If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments. Configure like so: ```ruby Split.configuration.experiments = { :button_color_experiment => { :alternatives => ["blue", "green"], :combined_experiments => ["button_color_on_signup", "button_color_on_login"] } } ``` Starting the combined test starts all combined experiments ```ruby ab_combined_test(:button_color_experiment) ``` Finish each combined test as normal ```ruby ab_finished(:button_color_on_login) ab_finished(:button_color_on_signup) ``` **Additional Configuration**: * Be sure to enable `allow_multiple_experiments` * In Sinatra include the CombinedExperimentsHelper ``` helpers Split::CombinedExperimentsHelper ``` ### DB failover solution Due to the fact that Redis has no automatic failover mechanism, it's possible to switch on the `db_failover` config option, so that `ab_test` and `ab_finished` will not crash in case of a db failure. `ab_test` always delivers alternative A (the first one) in that case. It's also possible to set a `db_failover_on_db_error` callback (proc) for example to log these errors via Rails.logger. ### Redis You may want to change the Redis host and port Split connects to, or set various other options at startup. Split has a `redis` setter which can be given a string or a Redis object. This means if you're already using Redis in your app, Split can re-use the existing connection. String: `Split.redis = 'redis://localhost:6379'` Redis: `Split.redis = $redis` For our rails app we have a `config/initializers/split.rb` file where we load `config/split.yml` by hand and set the Redis information appropriately. Here's our `config/split.yml`: ```yml development: redis://localhost:6379 test: redis://localhost:6379 staging: redis://redis1.example.com:6379 fi: redis://localhost:6379 production: redis://redis1.example.com:6379 ``` And our initializer: ```ruby split_config = YAML.load_file(Rails.root.join('config', 'split.yml')) Split.redis = split_config[Rails.env] ``` ### Redis Caching (v4.0+) In some high-volume usage scenarios, Redis load can be incurred by repeated fetches for fairly static data. Enabling caching will reduce this load. ```ruby Split.configuration.cache = true ```` This currently caches: - `Split::ExperimentCatalog.find` - `Split::Experiment.start_time` - `Split::Experiment.winner` ## Namespaces If you're running multiple, separate instances of Split you may want to namespace the keyspaces so they do not overlap. This is not unlike the approach taken by many memcached clients. This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace) library. To configure Split to use `Redis::Namespace`, do the following: 1. Add `redis-namespace` to your Gemfile: ```ruby gem 'redis-namespace' ``` 2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an initializer): ```ruby redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want Split.redis = Redis::Namespace.new(:your_namespace, redis: redis) ``` ## Outside of a Web Session Split provides the Helper module to facilitate running experiments inside web sessions. Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to conduct experiments that are not tied to a web session. ```ruby # create a new experiment experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') # create a new trial trial = Split::Trial.new(:experiment => experiment) # run trial trial.choose! # get the result, returns either red or blue trial.alternative.name # if the goal has been achieved, increment the successful completions for this alternative. if goal_achieved? trial.complete! end ``` ## Blogposts * [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) This algorithm will automatically weight the alternatives based on their relative performance, choosing the better-performing ones more often as trials are completed. `Split::Algorithms::BlockRandomization` is an algorithm that ensures equal participation across all alternatives. This algorithm will choose the alternative with the fewest participants. In the event of multiple minimum participant alternatives (i.e. starting a new "Block") the algorithm will choose a random alternative from those minimum participant alternatives. Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file. To change the algorithm globally for all experiments, use the following in your initializer: ```ruby Split.configure do |config| config.algorithm = Split::Algorithms::Whiplash end ``` ## Extensions - [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split. - [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics. - [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis). - [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test. - [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative. - [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests. ## Screencast Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split) ## Blogposts * [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)] <a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a> <a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a> <a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a> <a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a> <a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a> <a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a> <a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a> <a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a> <a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a> <a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a> <a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a> <a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a> <a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a> <a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a> <a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a> <a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a> <a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a> <a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a> <a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a> <a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a> <a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a> <a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a> <a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a> <a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a> <a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a> <a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a> <a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a> <a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a> <a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a> <a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)] <a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a> ## Contribute Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors. ### Development The source code is hosted at [GitHub](https://github.com/splitrb/split). Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues). You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby). ### Tests Run the tests like this: # Start a Redis server in another tab. redis-server bundle rake spec ### A Note on Patches and Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Add documentation if necessary. * Commit. Do not mess with the rakefile, version, or history. (If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.) * Send a pull request. Bonus points for topic branches. ### Code of Conduct Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ## Copyright [MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew). <MSG> Remove dead link, fixes #450 <DFF> @@ -824,7 +824,6 @@ Ryan bates has produced an excellent 10 minute screencast about split on the Rai ## Blogposts -* [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
0
Remove dead link, fixes #450
1
.md
md
mit
splitrb/split
10071972
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](https://www.codetriage.com/splitrb/split) > 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app. Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis. Split is designed to be hacker friendly, allowing for maximum customisation and extensibility. ## Install ### Requirements Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2. If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3) Split uses Redis as a datastore. Split only supports Redis 4.0 or greater. If you're on OS X, Homebrew is the simplest way to install Redis: ```bash brew install redis redis-server /usr/local/etc/redis.conf ``` You now have a Redis daemon running on port `6379`. ### Setup ```bash gem install split ``` #### Rails Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'. #### Sinatra To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app: ```ruby require 'split' class MySinatraApp < Sinatra::Base enable :sessions helpers Split::Helper get '/' do ... end ``` ## Usage To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments. `ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on. It can be used to render different templates, show different text or any other case based logic. `ab_finished` is used to make a completion of an experiment, or conversion. Example: View ```erb <% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %> <%= image_tag(button_file, alt: "Login!") %> <% end %> ``` Example: Controller ```ruby def register_new_user # See what level of free points maximizes users' decision to buy replacement points. @starter_points = ab_test(:new_user_free_points, '100', '200', '300') end ``` Example: Conversion tracking (in a controller!) ```ruby def buy_new_points # some business logic ab_finished(:new_user_free_points) end ``` Example: Conversion tracking (in a view) ```erb Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %> ``` You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki). ## Statistical Validity Split has two options for you to use to determine which alternative is the best. The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch. As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none). [Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience. The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test. Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day). ```ruby Split.configure do |config| config.winning_alternative_recalculation_interval = 3600 # 1 hour end ``` ## Extras ### Weighted alternatives Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested. To do this you can pass a weight with each alternative in the following ways: ```ruby ab_test(:homepage_design, {'Old' => 18}, {'New' => 2}) ab_test(:homepage_design, 'Old', {'New' => 1.0/9}) ab_test(:homepage_design, {'Old' => 9}, 'New') ``` This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1. ### Overriding alternatives For development and testing, you may wish to force your app to always return an alternative. You can do this by passing it as a parameter in the url. If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as: http://myawesomesite.com?ab_test[button_color]=red will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option. In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter. http://myawesomesite.com?SPLIT_DISABLE=true It is not required to send `SPLIT_DISABLE=false` to activate Split. ### Rspec Helper To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below: ```ruby # Create a file with these contents at 'spec/support/split_helper.rb' # and ensure it is `require`d in your rails_helper.rb or spec_helper.rb module SplitHelper # Force a specific experiment alternative to always be returned: # use_ab_test(signup_form: "single_page") # # Force alternatives for multiple experiments: # use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices") # def use_ab_test(alternatives_by_experiment) allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block| variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } block.call(variant) unless block.nil? variant end end end # Make the `use_ab_test` method available to all specs: RSpec.configure do |config| config.include SplitHelper end ``` Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example: ```ruby it "registers using experimental signup" do use_ab_test experiment_name: "alternative_name" post "/signups" ... end ``` ### Starting experiments manually By default new A/B tests will be active right after deployment. In case you would like to start new test a while after the deploy, you can do it by setting the `start_manually` configuration option to `true`. After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized. ### Reset after completion When a user completes a test their session is reset so that they may start the test again in the future. To stop this behaviour you can pass the following option to the `ab_finished` method: ```ruby ab_finished(:experiment_name, reset: false) ``` The user will then always see the alternative they started with. Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`. ### Reset experiments manually By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`. You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything. ### Multiple experiments at once By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests. To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = true end ``` This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another. To address this, setting the `allow_multiple_experiments` config option to 'control' like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = 'control' end ``` For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment. ### Experiment Persistence Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment. By default Split will store the tests for each user in the session. You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing. #### Cookies ```ruby Split.configure do |config| config.persistence = :cookie end ``` When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds). ```ruby Split.configure do |config| config.persistence = :cookie config.persistence_cookie_length = 2592000 # 30 days end ``` The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" } __Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API #### Redis Using Redis will allow ab_users to persist across sessions or machines. ```ruby Split.configure do |config| config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id }) # Equivalent # config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id) end ``` Options: * `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration) * `namespace`: separate namespace to store these persisted values (default "persistence") * `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments) #### Dual Adapter The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users. ```ruby cookie_adapter = Split::Persistence::CookieAdapter redis_adapter = Split::Persistence::RedisAdapter.with_config( lookup_by: -> (context) { context.send(:current_user).try(:id) }, expire_seconds: 2592000) Split.configure do |config| config.persistence = Split::Persistence::DualAdapter.with_config( logged_in: -> (context) { !context.send(:current_user).try(:id).nil? }, logged_in_adapter: redis_adapter, logged_out_adapter: cookie_adapter) config.persistence_cookie_length = 2592000 # 30 days end ``` #### Custom Adapter Your custom adapter needs to implement the same API as existing adapters. See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point. ```ruby Split.configure do |config| config.persistence = YourCustomAdapterClass end ``` ### Trial Event Hooks You can define methods that will be called at the same time as experiment alternative participation and goal completion. For example: ``` ruby Split.configure do |config| config.on_trial = :log_trial # run on every trial config.on_trial_choose = :log_trial_choose # run on trials with new users only config.on_trial_complete = :log_trial_complete end ``` Set these attributes to a method name available in the same context as the `ab_test` method. These methods should accept one argument, a `Trial` instance. ``` ruby def log_trial(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_choose(trial) logger.info "[new user] experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_complete(trial) logger.info "experiment=%s alternative=%s user=%s complete=true" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` #### Views If you are running `ab_test` from a view, you must define your event hook callback as a [helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method) in the controller: ``` ruby helper_method :log_trial_choose def log_trial_choose(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` ### Experiment Hooks You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split. For example: ``` ruby Split.configure do |config| # after experiment reset or deleted config.on_experiment_reset = -> (example) { # Do something on reset } config.on_experiment_delete = -> (experiment) { # Do something else on delete } # before experiment reset or deleted config.on_before_experiment_reset = -> (example) { # Do something on reset } config.on_before_experiment_delete = -> (experiment) { # Do something else on delete } # after experiment winner had been set config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose } end ``` ## Web Interface Split comes with a Sinatra-based front end to get an overview of how your experiments are doing. If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru` ```ruby require 'split/dashboard' run Rack::URLMap.new \ "/" => Your::App.new, "/split" => Split::Dashboard.new ``` However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile: ```ruby gem 'split', require: 'split/dashboard' ``` Then adding this to config/routes.rb ```ruby mount Split::Dashboard, at: 'split' ``` You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file) ```ruby # Rails apps or apps that already depend on activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end # Apps without activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end ``` You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following: ```ruby match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do request.env['warden'].authenticated? # are we authenticated? request.env['warden'].authenticate! # authenticate if not already # or even check any other condition such as request.env['warden'].user.is_admin? end ``` More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/) ### Screenshot ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## Configuration You can override the default configuration options of Split like so: ```ruby Split.configure do |config| config.db_failover = true # handle Redis errors gracefully config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) } config.allow_multiple_experiments = true config.enabled = true config.persistence = Split::Persistence::SessionAdapter #config.start_manually = false ## new test will have to be started manually from the admin panel. default false #config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes config.include_rails_helper = true config.redis = "redis://custom.redis.url:6380" end ``` Split looks for the Redis host in the environment variable `REDIS_URL` then defaults to `redis://localhost:6379` if not specified by configure block. On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to determine which env variable key to use when retrieving the host config. This defaults to `REDIS_URL`. ### Filtering In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users. Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic. ```ruby Split.configure do |config| # bot config config.robot_regex = /my_custom_robot_regex/ # or config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion" # IP config config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/ # or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? } config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) } end ``` ### Experiment configuration Instead of providing the experiment options inline, you can store them in a hash. This hash can control your experiment's alternatives, weights, algorithm and if the experiment resets once finished: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], resettable: false }, :my_second_experiment => { algorithm: 'Split::Algorithms::Whiplash', alternatives: [ { name: "a", percent: 67 }, { name: "b", percent: 33 } ] } } end ``` You can also store your experiments in a YAML file: ```ruby Split.configure do |config| config.experiments = YAML.load_file "config/experiments.yml" end ``` You can then define the YAML file like: ```yaml my_first_experiment: alternatives: - a - b my_second_experiment: alternatives: - name: a percent: 67 - name: b percent: 33 resettable: false ``` This simplifies the calls from your code: ```ruby ab_test(:my_first_experiment) ``` and: ```ruby ab_finished(:my_first_experiment) ``` You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"} } } } end ``` ```yaml my_first_experiment: alternatives: - a - b metadata: a: text: "Have a fantastic day" b: text: "Don't get hit by a bus" ``` This allows for some advanced experiment configuration using methods like: ```ruby trial.alternative.name # => "a" trial.metadata['text'] # => "Have a fantastic day" ``` or in views: ```erb <% ab_test("my_first_experiment") do |alternative, meta| %> <%= alternative %> <small><%= meta['text'] %></small> <% end %> ``` The keys used in meta data should be Strings #### Metrics You might wish to track generic metrics, such as conversions, and use those to complete multiple different experiments without adding more to your code. You can use the configuration hash to do this, thanks to the `:metric` option. ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metric: :my_metric } } end ``` Your code may then track a completion using the metric instead of the experiment name: ```ruby ab_finished(:my_metric) ``` You can also create a new metric by instantiating and saving a new Metric object. ```ruby Split::Metric.new(:my_metric) Split::Metric.save ``` #### Goals You might wish to allow an experiment to have multiple, distinguishable goals. The API to define goals for an experiment is this: ```ruby ab_test({link_color: ["purchase", "refund"]}, "red", "blue") ``` or you can define them in a configuration file: ```ruby Split.configure do |config| config.experiments = { link_color: { alternatives: ["red", "blue"], goals: ["purchase", "refund"] } } end ``` To complete a goal conversion, you do it like: ```ruby ab_finished(link_color: "purchase") ``` Note that if you pass additional options, that should be a separate hash: ```ruby ab_finished({ link_color: "purchase" }, reset: false) ``` **NOTE:** This does not mean that a single experiment can complete more than one goal. Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.) **Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion"). **Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK. **Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK. #### Combined Experiments If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments. Configure like so: ```ruby Split.configuration.experiments = { :button_color_experiment => { :alternatives => ["blue", "green"], :combined_experiments => ["button_color_on_signup", "button_color_on_login"] } } ``` Starting the combined test starts all combined experiments ```ruby ab_combined_test(:button_color_experiment) ``` Finish each combined test as normal ```ruby ab_finished(:button_color_on_login) ab_finished(:button_color_on_signup) ``` **Additional Configuration**: * Be sure to enable `allow_multiple_experiments` * In Sinatra include the CombinedExperimentsHelper ``` helpers Split::CombinedExperimentsHelper ``` ### DB failover solution Due to the fact that Redis has no automatic failover mechanism, it's possible to switch on the `db_failover` config option, so that `ab_test` and `ab_finished` will not crash in case of a db failure. `ab_test` always delivers alternative A (the first one) in that case. It's also possible to set a `db_failover_on_db_error` callback (proc) for example to log these errors via Rails.logger. ### Redis You may want to change the Redis host and port Split connects to, or set various other options at startup. Split has a `redis` setter which can be given a string or a Redis object. This means if you're already using Redis in your app, Split can re-use the existing connection. String: `Split.redis = 'redis://localhost:6379'` Redis: `Split.redis = $redis` For our rails app we have a `config/initializers/split.rb` file where we load `config/split.yml` by hand and set the Redis information appropriately. Here's our `config/split.yml`: ```yml development: redis://localhost:6379 test: redis://localhost:6379 staging: redis://redis1.example.com:6379 fi: redis://localhost:6379 production: redis://redis1.example.com:6379 ``` And our initializer: ```ruby split_config = YAML.load_file(Rails.root.join('config', 'split.yml')) Split.redis = split_config[Rails.env] ``` ### Redis Caching (v4.0+) In some high-volume usage scenarios, Redis load can be incurred by repeated fetches for fairly static data. Enabling caching will reduce this load. ```ruby Split.configuration.cache = true ```` This currently caches: - `Split::ExperimentCatalog.find` - `Split::Experiment.start_time` - `Split::Experiment.winner` ## Namespaces If you're running multiple, separate instances of Split you may want to namespace the keyspaces so they do not overlap. This is not unlike the approach taken by many memcached clients. This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace) library. To configure Split to use `Redis::Namespace`, do the following: 1. Add `redis-namespace` to your Gemfile: ```ruby gem 'redis-namespace' ``` 2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an initializer): ```ruby redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want Split.redis = Redis::Namespace.new(:your_namespace, redis: redis) ``` ## Outside of a Web Session Split provides the Helper module to facilitate running experiments inside web sessions. Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to conduct experiments that are not tied to a web session. ```ruby # create a new experiment experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') # create a new trial trial = Split::Trial.new(:experiment => experiment) # run trial trial.choose! # get the result, returns either red or blue trial.alternative.name # if the goal has been achieved, increment the successful completions for this alternative. if goal_achieved? trial.complete! end ``` ## Blogposts * [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) This algorithm will automatically weight the alternatives based on their relative performance, choosing the better-performing ones more often as trials are completed. `Split::Algorithms::BlockRandomization` is an algorithm that ensures equal participation across all alternatives. This algorithm will choose the alternative with the fewest participants. In the event of multiple minimum participant alternatives (i.e. starting a new "Block") the algorithm will choose a random alternative from those minimum participant alternatives. Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file. To change the algorithm globally for all experiments, use the following in your initializer: ```ruby Split.configure do |config| config.algorithm = Split::Algorithms::Whiplash end ``` ## Extensions - [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split. - [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics. - [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis). - [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test. - [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative. - [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests. ## Screencast Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split) ## Blogposts * [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)] <a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a> <a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a> <a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a> <a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a> <a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a> <a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a> <a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a> <a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a> <a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a> <a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a> <a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a> <a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a> <a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a> <a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a> <a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a> <a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a> <a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a> <a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a> <a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a> <a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a> <a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a> <a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a> <a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a> <a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a> <a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a> <a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a> <a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a> <a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a> <a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a> <a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)] <a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a> ## Contribute Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors. ### Development The source code is hosted at [GitHub](https://github.com/splitrb/split). Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues). You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby). ### Tests Run the tests like this: # Start a Redis server in another tab. redis-server bundle rake spec ### A Note on Patches and Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Add documentation if necessary. * Commit. Do not mess with the rakefile, version, or history. (If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.) * Send a pull request. Bonus points for topic branches. ### Code of Conduct Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ## Copyright [MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew). <MSG> Remove dead link, fixes #450 <DFF> @@ -824,7 +824,6 @@ Ryan bates has produced an excellent 10 minute screencast about split on the Rai ## Blogposts -* [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
0
Remove dead link, fixes #450
1
.md
md
mit
splitrb/split
10071973
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](https://www.codetriage.com/splitrb/split) > 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app. Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis. Split is designed to be hacker friendly, allowing for maximum customisation and extensibility. ## Install ### Requirements Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2. If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3) Split uses Redis as a datastore. Split only supports Redis 4.0 or greater. If you're on OS X, Homebrew is the simplest way to install Redis: ```bash brew install redis redis-server /usr/local/etc/redis.conf ``` You now have a Redis daemon running on port `6379`. ### Setup ```bash gem install split ``` #### Rails Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'. #### Sinatra To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app: ```ruby require 'split' class MySinatraApp < Sinatra::Base enable :sessions helpers Split::Helper get '/' do ... end ``` ## Usage To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments. `ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on. It can be used to render different templates, show different text or any other case based logic. `ab_finished` is used to make a completion of an experiment, or conversion. Example: View ```erb <% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %> <%= image_tag(button_file, alt: "Login!") %> <% end %> ``` Example: Controller ```ruby def register_new_user # See what level of free points maximizes users' decision to buy replacement points. @starter_points = ab_test(:new_user_free_points, '100', '200', '300') end ``` Example: Conversion tracking (in a controller!) ```ruby def buy_new_points # some business logic ab_finished(:new_user_free_points) end ``` Example: Conversion tracking (in a view) ```erb Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %> ``` You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki). ## Statistical Validity Split has two options for you to use to determine which alternative is the best. The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch. As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none). [Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience. The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test. Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day). ```ruby Split.configure do |config| config.winning_alternative_recalculation_interval = 3600 # 1 hour end ``` ## Extras ### Weighted alternatives Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested. To do this you can pass a weight with each alternative in the following ways: ```ruby ab_test(:homepage_design, {'Old' => 18}, {'New' => 2}) ab_test(:homepage_design, 'Old', {'New' => 1.0/9}) ab_test(:homepage_design, {'Old' => 9}, 'New') ``` This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1. ### Overriding alternatives For development and testing, you may wish to force your app to always return an alternative. You can do this by passing it as a parameter in the url. If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as: http://myawesomesite.com?ab_test[button_color]=red will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option. In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter. http://myawesomesite.com?SPLIT_DISABLE=true It is not required to send `SPLIT_DISABLE=false` to activate Split. ### Rspec Helper To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below: ```ruby # Create a file with these contents at 'spec/support/split_helper.rb' # and ensure it is `require`d in your rails_helper.rb or spec_helper.rb module SplitHelper # Force a specific experiment alternative to always be returned: # use_ab_test(signup_form: "single_page") # # Force alternatives for multiple experiments: # use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices") # def use_ab_test(alternatives_by_experiment) allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block| variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } block.call(variant) unless block.nil? variant end end end # Make the `use_ab_test` method available to all specs: RSpec.configure do |config| config.include SplitHelper end ``` Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example: ```ruby it "registers using experimental signup" do use_ab_test experiment_name: "alternative_name" post "/signups" ... end ``` ### Starting experiments manually By default new A/B tests will be active right after deployment. In case you would like to start new test a while after the deploy, you can do it by setting the `start_manually` configuration option to `true`. After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized. ### Reset after completion When a user completes a test their session is reset so that they may start the test again in the future. To stop this behaviour you can pass the following option to the `ab_finished` method: ```ruby ab_finished(:experiment_name, reset: false) ``` The user will then always see the alternative they started with. Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`. ### Reset experiments manually By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`. You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything. ### Multiple experiments at once By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests. To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = true end ``` This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another. To address this, setting the `allow_multiple_experiments` config option to 'control' like so: ```ruby Split.configure do |config| config.allow_multiple_experiments = 'control' end ``` For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment. ### Experiment Persistence Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment. By default Split will store the tests for each user in the session. You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing. #### Cookies ```ruby Split.configure do |config| config.persistence = :cookie end ``` When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds). ```ruby Split.configure do |config| config.persistence = :cookie config.persistence_cookie_length = 2592000 # 30 days end ``` The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" } __Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API #### Redis Using Redis will allow ab_users to persist across sessions or machines. ```ruby Split.configure do |config| config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id }) # Equivalent # config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id) end ``` Options: * `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration) * `namespace`: separate namespace to store these persisted values (default "persistence") * `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments) #### Dual Adapter The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users. ```ruby cookie_adapter = Split::Persistence::CookieAdapter redis_adapter = Split::Persistence::RedisAdapter.with_config( lookup_by: -> (context) { context.send(:current_user).try(:id) }, expire_seconds: 2592000) Split.configure do |config| config.persistence = Split::Persistence::DualAdapter.with_config( logged_in: -> (context) { !context.send(:current_user).try(:id).nil? }, logged_in_adapter: redis_adapter, logged_out_adapter: cookie_adapter) config.persistence_cookie_length = 2592000 # 30 days end ``` #### Custom Adapter Your custom adapter needs to implement the same API as existing adapters. See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point. ```ruby Split.configure do |config| config.persistence = YourCustomAdapterClass end ``` ### Trial Event Hooks You can define methods that will be called at the same time as experiment alternative participation and goal completion. For example: ``` ruby Split.configure do |config| config.on_trial = :log_trial # run on every trial config.on_trial_choose = :log_trial_choose # run on trials with new users only config.on_trial_complete = :log_trial_complete end ``` Set these attributes to a method name available in the same context as the `ab_test` method. These methods should accept one argument, a `Trial` instance. ``` ruby def log_trial(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_choose(trial) logger.info "[new user] experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end def log_trial_complete(trial) logger.info "experiment=%s alternative=%s user=%s complete=true" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` #### Views If you are running `ab_test` from a view, you must define your event hook callback as a [helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method) in the controller: ``` ruby helper_method :log_trial_choose def log_trial_choose(trial) logger.info "experiment=%s alternative=%s user=%s" % [ trial.experiment.name, trial.alternative, current_user.id ] end ``` ### Experiment Hooks You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split. For example: ``` ruby Split.configure do |config| # after experiment reset or deleted config.on_experiment_reset = -> (example) { # Do something on reset } config.on_experiment_delete = -> (experiment) { # Do something else on delete } # before experiment reset or deleted config.on_before_experiment_reset = -> (example) { # Do something on reset } config.on_before_experiment_delete = -> (experiment) { # Do something else on delete } # after experiment winner had been set config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose } end ``` ## Web Interface Split comes with a Sinatra-based front end to get an overview of how your experiments are doing. If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru` ```ruby require 'split/dashboard' run Rack::URLMap.new \ "/" => Your::App.new, "/split" => Split::Dashboard.new ``` However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile: ```ruby gem 'split', require: 'split/dashboard' ``` Then adding this to config/routes.rb ```ruby mount Split::Dashboard, at: 'split' ``` You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file) ```ruby # Rails apps or apps that already depend on activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end # Apps without activesupport Split::Dashboard.use Rack::Auth::Basic do |username, password| # Protect against timing attacks: # - Use & (do not use &&) so that it doesn't short circuit. # - Use digests to stop length information leaking Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) & Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"])) end ``` You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following: ```ruby match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do request.env['warden'].authenticated? # are we authenticated? request.env['warden'].authenticate! # authenticate if not already # or even check any other condition such as request.env['warden'].user.is_admin? end ``` More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/) ### Screenshot ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## Configuration You can override the default configuration options of Split like so: ```ruby Split.configure do |config| config.db_failover = true # handle Redis errors gracefully config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) } config.allow_multiple_experiments = true config.enabled = true config.persistence = Split::Persistence::SessionAdapter #config.start_manually = false ## new test will have to be started manually from the admin panel. default false #config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes config.include_rails_helper = true config.redis = "redis://custom.redis.url:6380" end ``` Split looks for the Redis host in the environment variable `REDIS_URL` then defaults to `redis://localhost:6379` if not specified by configure block. On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to determine which env variable key to use when retrieving the host config. This defaults to `REDIS_URL`. ### Filtering In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users. Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic. ```ruby Split.configure do |config| # bot config config.robot_regex = /my_custom_robot_regex/ # or config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion" # IP config config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/ # or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? } config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) } end ``` ### Experiment configuration Instead of providing the experiment options inline, you can store them in a hash. This hash can control your experiment's alternatives, weights, algorithm and if the experiment resets once finished: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], resettable: false }, :my_second_experiment => { algorithm: 'Split::Algorithms::Whiplash', alternatives: [ { name: "a", percent: 67 }, { name: "b", percent: 33 } ] } } end ``` You can also store your experiments in a YAML file: ```ruby Split.configure do |config| config.experiments = YAML.load_file "config/experiments.yml" end ``` You can then define the YAML file like: ```yaml my_first_experiment: alternatives: - a - b my_second_experiment: alternatives: - name: a percent: 67 - name: b percent: 33 resettable: false ``` This simplifies the calls from your code: ```ruby ab_test(:my_first_experiment) ``` and: ```ruby ab_finished(:my_first_experiment) ``` You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour: ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"} } } } end ``` ```yaml my_first_experiment: alternatives: - a - b metadata: a: text: "Have a fantastic day" b: text: "Don't get hit by a bus" ``` This allows for some advanced experiment configuration using methods like: ```ruby trial.alternative.name # => "a" trial.metadata['text'] # => "Have a fantastic day" ``` or in views: ```erb <% ab_test("my_first_experiment") do |alternative, meta| %> <%= alternative %> <small><%= meta['text'] %></small> <% end %> ``` The keys used in meta data should be Strings #### Metrics You might wish to track generic metrics, such as conversions, and use those to complete multiple different experiments without adding more to your code. You can use the configuration hash to do this, thanks to the `:metric` option. ```ruby Split.configure do |config| config.experiments = { my_first_experiment: { alternatives: ["a", "b"], metric: :my_metric } } end ``` Your code may then track a completion using the metric instead of the experiment name: ```ruby ab_finished(:my_metric) ``` You can also create a new metric by instantiating and saving a new Metric object. ```ruby Split::Metric.new(:my_metric) Split::Metric.save ``` #### Goals You might wish to allow an experiment to have multiple, distinguishable goals. The API to define goals for an experiment is this: ```ruby ab_test({link_color: ["purchase", "refund"]}, "red", "blue") ``` or you can define them in a configuration file: ```ruby Split.configure do |config| config.experiments = { link_color: { alternatives: ["red", "blue"], goals: ["purchase", "refund"] } } end ``` To complete a goal conversion, you do it like: ```ruby ab_finished(link_color: "purchase") ``` Note that if you pass additional options, that should be a separate hash: ```ruby ab_finished({ link_color: "purchase" }, reset: false) ``` **NOTE:** This does not mean that a single experiment can complete more than one goal. Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.) **Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion"). **Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK. **Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK. #### Combined Experiments If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments. Configure like so: ```ruby Split.configuration.experiments = { :button_color_experiment => { :alternatives => ["blue", "green"], :combined_experiments => ["button_color_on_signup", "button_color_on_login"] } } ``` Starting the combined test starts all combined experiments ```ruby ab_combined_test(:button_color_experiment) ``` Finish each combined test as normal ```ruby ab_finished(:button_color_on_login) ab_finished(:button_color_on_signup) ``` **Additional Configuration**: * Be sure to enable `allow_multiple_experiments` * In Sinatra include the CombinedExperimentsHelper ``` helpers Split::CombinedExperimentsHelper ``` ### DB failover solution Due to the fact that Redis has no automatic failover mechanism, it's possible to switch on the `db_failover` config option, so that `ab_test` and `ab_finished` will not crash in case of a db failure. `ab_test` always delivers alternative A (the first one) in that case. It's also possible to set a `db_failover_on_db_error` callback (proc) for example to log these errors via Rails.logger. ### Redis You may want to change the Redis host and port Split connects to, or set various other options at startup. Split has a `redis` setter which can be given a string or a Redis object. This means if you're already using Redis in your app, Split can re-use the existing connection. String: `Split.redis = 'redis://localhost:6379'` Redis: `Split.redis = $redis` For our rails app we have a `config/initializers/split.rb` file where we load `config/split.yml` by hand and set the Redis information appropriately. Here's our `config/split.yml`: ```yml development: redis://localhost:6379 test: redis://localhost:6379 staging: redis://redis1.example.com:6379 fi: redis://localhost:6379 production: redis://redis1.example.com:6379 ``` And our initializer: ```ruby split_config = YAML.load_file(Rails.root.join('config', 'split.yml')) Split.redis = split_config[Rails.env] ``` ### Redis Caching (v4.0+) In some high-volume usage scenarios, Redis load can be incurred by repeated fetches for fairly static data. Enabling caching will reduce this load. ```ruby Split.configuration.cache = true ```` This currently caches: - `Split::ExperimentCatalog.find` - `Split::Experiment.start_time` - `Split::Experiment.winner` ## Namespaces If you're running multiple, separate instances of Split you may want to namespace the keyspaces so they do not overlap. This is not unlike the approach taken by many memcached clients. This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace) library. To configure Split to use `Redis::Namespace`, do the following: 1. Add `redis-namespace` to your Gemfile: ```ruby gem 'redis-namespace' ``` 2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an initializer): ```ruby redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want Split.redis = Redis::Namespace.new(:your_namespace, redis: redis) ``` ## Outside of a Web Session Split provides the Helper module to facilitate running experiments inside web sessions. Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to conduct experiments that are not tied to a web session. ```ruby # create a new experiment experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue') # create a new trial trial = Split::Trial.new(:experiment => experiment) # run trial trial.choose! # get the result, returns either red or blue trial.alternative.name # if the goal has been achieved, increment the successful completions for this alternative. if goal_achieved? trial.complete! end ``` ## Blogposts * [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) This algorithm will automatically weight the alternatives based on their relative performance, choosing the better-performing ones more often as trials are completed. `Split::Algorithms::BlockRandomization` is an algorithm that ensures equal participation across all alternatives. This algorithm will choose the alternative with the fewest participants. In the event of multiple minimum participant alternatives (i.e. starting a new "Block") the algorithm will choose a random alternative from those minimum participant alternatives. Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file. To change the algorithm globally for all experiments, use the following in your initializer: ```ruby Split.configure do |config| config.algorithm = Split::Algorithms::Whiplash end ``` ## Extensions - [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split. - [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics. - [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis). - [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test. - [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative. - [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests. ## Screencast Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split) ## Blogposts * [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html) ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)] <a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a> <a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a> <a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a> <a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a> <a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a> <a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a> <a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a> <a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a> <a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a> <a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a> <a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a> <a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a> <a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a> <a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a> <a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a> <a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a> <a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a> <a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a> <a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a> <a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a> <a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a> <a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a> <a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a> <a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a> <a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a> <a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a> <a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a> <a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a> <a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a> <a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)] <a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a> ## Contribute Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors. ### Development The source code is hosted at [GitHub](https://github.com/splitrb/split). Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues). You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby). ### Tests Run the tests like this: # Start a Redis server in another tab. redis-server bundle rake spec ### A Note on Patches and Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Add documentation if necessary. * Commit. Do not mess with the rakefile, version, or history. (If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.) * Send a pull request. Bonus points for topic branches. ### Code of Conduct Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ## Copyright [MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew). <MSG> Remove dead link, fixes #450 <DFF> @@ -824,7 +824,6 @@ Ryan bates has produced an excellent 10 minute screencast about split on the Rai ## Blogposts -* [A/B Testing with Split in Ruby on Rails](http://grinnick.com/posts/a-b-testing-with-split-in-ruby-on-rails) * [Recipe: A/B testing with KISSMetrics and the split gem](http://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem) * [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
0
Remove dead link, fixes #450
1
.md
md
mit
splitrb/split
10071974
<NME> index.ts <BEF> import Scanner, { isAlphaWord, isAlpha, isNumber, isAlphaNumericWord, isSpace, isQuote } from '@emmetio/scanner'; import { AllTokens, Literal, OperatorType, NumberValue, ColorValue, WhiteSpace, Operator, Bracket, StringValue, Field } from './tokens'; import { Chars } from './utils'; export * from './tokens'; export default function tokenize(abbr: string, isValue?: boolean): AllTokens[] { let brackets = 0; let token: AllTokens | undefined; const scanner = new Scanner(abbr); const tokens: AllTokens[] = []; while (!scanner.eof()) { token = getToken(scanner, brackets === 0 && !isValue); if (!token) { throw scanner.error('Unexpected character'); } if (token.type === 'Bracket') { if (!brackets && token.open) { mergeTokens(scanner, tokens); } brackets += token.open ? 1 : -1; if (brackets < 0) { throw scanner.error('Unexpected bracket', token.start); } } tokens.push(token); // Forcibly consume next operator after unit-less numeric value or color: // next dash `-` must be used as value delimiter if (shouldConsumeDashAfter(token) && (token = operator(scanner))) { tokens.push(token); } } return tokens; } /** * Returns next token from given scanner, if possible */ export function getToken(scanner: Scanner, short?: boolean) { return field(scanner) || numberValue(scanner) || colorValue(scanner) || stringValue(scanner) || bracket(scanner) || operator(scanner) || whiteSpace(scanner) || literal(scanner, short); } function field(scanner: Scanner): Field | undefined { const start = scanner.pos; if (scanner.eat(Chars.Dollar) && scanner.eat(Chars.CurlyBracketOpen)) { scanner.start = scanner.pos; let index: number | undefined; let name: string = ''; if (scanner.eatWhile(isNumber)) { // It’s a field index = Number(scanner.current()); name = scanner.eat(Chars.Colon) ? consumePlaceholder(scanner) : ''; } else if (isAlpha(scanner.peek())) { // It’s a variable name = consumePlaceholder(scanner); } if (scanner.eat(Chars.CurlyBracketClose)) { return { type: 'Field', index, name, start, end: scanner.pos }; } throw scanner.error('Expecting }'); } // If we reached here then there’s no valid field here, revert // back to starting position scanner.pos = start; } /** * Consumes a placeholder: value right after `:` in field. Could be empty */ function consumePlaceholder(stream: Scanner): string { const stack: number[] = []; stream.start = stream.pos; while (!stream.eof()) { if (stream.eat(Chars.CurlyBracketOpen)) { stack.push(stream.pos); } else if (stream.eat(Chars.CurlyBracketClose)) { if (!stack.length) { stream.pos--; break; } stack.pop(); } else { stream.pos++; } } if (stack.length) { stream.pos = stack.pop()!; throw stream.error(`Expecting }`); } return stream.current(); } /** * Consumes literal from given scanner * @param short Use short notation for consuming value. * The difference between “short” and “full” notation is that first one uses * alpha characters only and used for extracting keywords from abbreviation, * while “full” notation also supports numbers and dashes */ function literal(scanner: Scanner, short?: boolean): Literal | undefined { const start = scanner.pos; if (scanner.eat(isIdentPrefix)) { // SCSS or LESS variable // NB a bit dirty hack: if abbreviation starts with identifier prefix, // consume alpha characters only to allow embedded variables scanner.eatWhile(start ? isKeyword : isLiteral); } else if (scanner.eat(isAlphaWord)) { scanner.eatWhile(short ? isLiteral : isKeyword); } else { // Allow dots only at the beginning of literal scanner.eat(Chars.Dot); scanner.eatWhile(isLiteral); } if (start !== scanner.pos) { scanner.start = start; return createLiteral(scanner, scanner.start = start); } } function createLiteral(scanner: Scanner, start = scanner.start, end = scanner.pos): Literal { return { type: 'Literal', value: scanner.substring(start, end), start, end }; } /** * Consumes numeric CSS value (number with optional unit) from current stream, * if possible */ function numberValue(scanner: Scanner): NumberValue | undefined { const start = scanner.pos; if (consumeNumber(scanner)) { scanner.start = start; const rawValue = scanner.current(); // eat unit, which can be a % or alpha word scanner.start = scanner.pos; scanner.eat(Chars.Percent) || scanner.eatWhile(isAlphaWord); return { type: 'NumberValue', value: Number(rawValue), rawValue, unit: scanner.current(), start, end: scanner.pos }; } } /** * Consumes quoted string value from given scanner */ function stringValue(scanner: Scanner): StringValue | undefined { const ch = scanner.peek(); const start = scanner.pos; let finished = false; if (isQuote(ch)) { scanner.pos++; while (!scanner.eof()) { // Do not throw error on malformed string if (scanner.eat(ch)) { finished = true; break; } else { scanner.pos++; } } scanner.start = start; return { type: 'StringValue', value: scanner.substring(start + 1, scanner.pos - (finished ? 1 : 0)), quote: ch === Chars.SingleQuote ? 'single' : 'double', start, end: scanner.pos }; } } /** * Consumes a color token from given string */ // a hex color can be followed by `.num` alpha value scanner.start = scanner.pos; if (scanner.eat(Chars.Dot)) { if (scanner.eatWhile(isNumber)) { alpha = scanner.current(); } else { throw scanner.error('Unexpected character for alpha value of color'); } } const { r, g, b, a } = parseColor(color, alpha); const valueStart = scanner.pos; let color = ''; let alpha = ''; if (scanner.eatWhile(isHex)) { color = scanner.substring(valueStart, scanner.pos); alpha = colorAlpha(scanner); } else if (scanner.eat(Chars.Transparent)) { color = '0'; alpha = colorAlpha(scanner) || '0'; } else { alpha = colorAlpha(scanner); } if (color || alpha || scanner.eof()) { const { r, g, b, a } = parseColor(color, alpha); return { type: 'ColorValue', r, g, b, a, raw: scanner.substring(start + 1, scanner.pos), start, end: scanner.pos }; } else { // Consumed # but no actual value: invalid color value, treat it as literal return createLiteral(scanner, start); } } scanner.pos = start; } /** * Consumes alpha value of color: `.1` */ function colorAlpha(scanner: Scanner): string { const start = scanner.pos; if (scanner.eat(Chars.Dot)) { scanner.start = start; if (scanner.eatWhile(isNumber)) { return scanner.current(); } return '1'; } return ''; } /** * Consumes white space characters as string literal from given scanner */ function whiteSpace(scanner: Scanner): WhiteSpace | undefined { const start = scanner.pos; if (scanner.eatWhile(isSpace)) { return { type: 'WhiteSpace', start, end: scanner.pos }; } } /** * Consumes bracket from given scanner */ function bracket(scanner: Scanner): Bracket | undefined { const ch = scanner.peek(); if (isBracket(ch)) { return { type: 'Bracket', open: ch === Chars.RoundBracketOpen, start: scanner.pos++, end: scanner.pos }; } } /** * Consumes operator from given scanner */ function operator(scanner: Scanner): Operator | undefined { const op = operatorType(scanner.peek()); if (op) { return { type: 'Operator', operator: op, start: scanner.pos++, end: scanner.pos }; } } /** * Eats number value from given stream * @return Returns `true` if number was consumed */ function consumeNumber(stream: Scanner): boolean { const start = stream.pos; stream.eat(Chars.Dash); const afterNegative = stream.pos; const hasDecimal = stream.eatWhile(isNumber); const prevPos = stream.pos; if (stream.eat(Chars.Dot)) { // It’s perfectly valid to have numbers like `1.`, which enforces // value to float unit type const hasFloat = stream.eatWhile(isNumber); if (!hasDecimal && !hasFloat) { // Lone dot stream.pos = prevPos; } } // Edge case: consumed dash only: not a number, bail-out if (stream.pos === afterNegative) { stream.pos = start; } return stream.pos !== start; } function isIdentPrefix(code: number): boolean { return code === Chars.At || code === Chars.Dollar; } /** * If given character is an operator, returns it’s type */ function operatorType(ch: number): OperatorType | undefined { return (ch === Chars.Sibling && OperatorType.Sibling) || (ch === Chars.Excl && OperatorType.Important) || (ch === Chars.Comma && OperatorType.ArgumentDelimiter) || (ch === Chars.Colon && OperatorType.PropertyDelimiter) || (ch === Chars.Dash && OperatorType.ValueDelimiter) || void 0; } /** * Check if given code is a hex value (/0-9a-f/) */ function isHex(code: number): boolean { return isNumber(code) || isAlpha(code, 65, 70); // A-F } function isKeyword(code: number): boolean { return isAlphaNumericWord(code) || code === Chars.Dash; } function isBracket(code: number) { return code === Chars.RoundBracketOpen || code === Chars.RoundBracketClose; } function isLiteral(code: number) { return isAlphaWord(code) || code === Chars.Percent || code === Chars.Slash; } /** * Parses given color value from abbreviation into RGBA format */ function parseColor(value: string, alpha?: string): { r: number, g: number, b: number, a: number } { let r = '0'; let g = '0'; let b = '0'; let a = Number(alpha != null && alpha !== '' ? alpha : 1); if (value === 't') { a = 0; } else { switch (value.length) { case 0: break; case 1: r = g = b = value + value; break; case 2: r = g = b = value; break; case 3: r = value[0] + value[0]; g = value[1] + value[1]; b = value[2] + value[2]; break; default: value += value; r = value.slice(0, 2); g = value.slice(2, 4); b = value.slice(4, 6); } } return { r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), a }; } /** * Check if scanner reader must consume dash after given token. * Used in cases where user must explicitly separate numeric values */ function shouldConsumeDashAfter(token: AllTokens): boolean { return token.type === 'ColorValue' || (token.type === 'NumberValue' && !token.unit); } /** * Merges last adjacent tokens into a single literal. * This function is used to overcome edge case when function name was parsed * as a list of separate tokens. For example, a `scale3d()` value will be * parsed as literal and number tokens (`scale` and `3d`) which is a perfectly * valid abbreviation but undesired result. This function will detect last adjacent * literal and number values and combine them into single literal */ function mergeTokens(scanner: Scanner, tokens: AllTokens[]) { let start = 0; let end = 0; while (tokens.length) { const token = last(tokens)!; if (token.type === 'Literal' || token.type === 'NumberValue') { start = token.start!; if (!end) { end = token.end!; } tokens.pop(); } else { break; } } if (start !== end) { tokens.push(createLiteral(scanner, start, end)); } } function last<T>(arr: T[]): T | undefined { return arr[arr.length - 1]; } <MSG> [stylesheet] Do not throw error on empty alpha color value <DFF> @@ -216,12 +216,8 @@ function colorValue(scanner: Scanner): ColorValue | undefined { // a hex color can be followed by `.num` alpha value scanner.start = scanner.pos; - if (scanner.eat(Chars.Dot)) { - if (scanner.eatWhile(isNumber)) { - alpha = scanner.current(); - } else { - throw scanner.error('Unexpected character for alpha value of color'); - } + if (scanner.eat(Chars.Dot) && scanner.eatWhile(isNumber)) { + alpha = scanner.current(); } const { r, g, b, a } = parseColor(color, alpha);
2
[stylesheet] Do not throw error on empty alpha color value
6
.ts
ts
mit
emmetio/emmet
10071975
<NME> index.ts <BEF> import Scanner, { isAlphaWord, isAlpha, isNumber, isAlphaNumericWord, isSpace, isQuote } from '@emmetio/scanner'; import { AllTokens, Literal, OperatorType, NumberValue, ColorValue, WhiteSpace, Operator, Bracket, StringValue, Field } from './tokens'; import { Chars } from './utils'; export * from './tokens'; export default function tokenize(abbr: string, isValue?: boolean): AllTokens[] { let brackets = 0; let token: AllTokens | undefined; const scanner = new Scanner(abbr); const tokens: AllTokens[] = []; while (!scanner.eof()) { token = getToken(scanner, brackets === 0 && !isValue); if (!token) { throw scanner.error('Unexpected character'); } if (token.type === 'Bracket') { if (!brackets && token.open) { mergeTokens(scanner, tokens); } brackets += token.open ? 1 : -1; if (brackets < 0) { throw scanner.error('Unexpected bracket', token.start); } } tokens.push(token); // Forcibly consume next operator after unit-less numeric value or color: // next dash `-` must be used as value delimiter if (shouldConsumeDashAfter(token) && (token = operator(scanner))) { tokens.push(token); } } return tokens; } /** * Returns next token from given scanner, if possible */ export function getToken(scanner: Scanner, short?: boolean) { return field(scanner) || numberValue(scanner) || colorValue(scanner) || stringValue(scanner) || bracket(scanner) || operator(scanner) || whiteSpace(scanner) || literal(scanner, short); } function field(scanner: Scanner): Field | undefined { const start = scanner.pos; if (scanner.eat(Chars.Dollar) && scanner.eat(Chars.CurlyBracketOpen)) { scanner.start = scanner.pos; let index: number | undefined; let name: string = ''; if (scanner.eatWhile(isNumber)) { // It’s a field index = Number(scanner.current()); name = scanner.eat(Chars.Colon) ? consumePlaceholder(scanner) : ''; } else if (isAlpha(scanner.peek())) { // It’s a variable name = consumePlaceholder(scanner); } if (scanner.eat(Chars.CurlyBracketClose)) { return { type: 'Field', index, name, start, end: scanner.pos }; } throw scanner.error('Expecting }'); } // If we reached here then there’s no valid field here, revert // back to starting position scanner.pos = start; } /** * Consumes a placeholder: value right after `:` in field. Could be empty */ function consumePlaceholder(stream: Scanner): string { const stack: number[] = []; stream.start = stream.pos; while (!stream.eof()) { if (stream.eat(Chars.CurlyBracketOpen)) { stack.push(stream.pos); } else if (stream.eat(Chars.CurlyBracketClose)) { if (!stack.length) { stream.pos--; break; } stack.pop(); } else { stream.pos++; } } if (stack.length) { stream.pos = stack.pop()!; throw stream.error(`Expecting }`); } return stream.current(); } /** * Consumes literal from given scanner * @param short Use short notation for consuming value. * The difference between “short” and “full” notation is that first one uses * alpha characters only and used for extracting keywords from abbreviation, * while “full” notation also supports numbers and dashes */ function literal(scanner: Scanner, short?: boolean): Literal | undefined { const start = scanner.pos; if (scanner.eat(isIdentPrefix)) { // SCSS or LESS variable // NB a bit dirty hack: if abbreviation starts with identifier prefix, // consume alpha characters only to allow embedded variables scanner.eatWhile(start ? isKeyword : isLiteral); } else if (scanner.eat(isAlphaWord)) { scanner.eatWhile(short ? isLiteral : isKeyword); } else { // Allow dots only at the beginning of literal scanner.eat(Chars.Dot); scanner.eatWhile(isLiteral); } if (start !== scanner.pos) { scanner.start = start; return createLiteral(scanner, scanner.start = start); } } function createLiteral(scanner: Scanner, start = scanner.start, end = scanner.pos): Literal { return { type: 'Literal', value: scanner.substring(start, end), start, end }; } /** * Consumes numeric CSS value (number with optional unit) from current stream, * if possible */ function numberValue(scanner: Scanner): NumberValue | undefined { const start = scanner.pos; if (consumeNumber(scanner)) { scanner.start = start; const rawValue = scanner.current(); // eat unit, which can be a % or alpha word scanner.start = scanner.pos; scanner.eat(Chars.Percent) || scanner.eatWhile(isAlphaWord); return { type: 'NumberValue', value: Number(rawValue), rawValue, unit: scanner.current(), start, end: scanner.pos }; } } /** * Consumes quoted string value from given scanner */ function stringValue(scanner: Scanner): StringValue | undefined { const ch = scanner.peek(); const start = scanner.pos; let finished = false; if (isQuote(ch)) { scanner.pos++; while (!scanner.eof()) { // Do not throw error on malformed string if (scanner.eat(ch)) { finished = true; break; } else { scanner.pos++; } } scanner.start = start; return { type: 'StringValue', value: scanner.substring(start + 1, scanner.pos - (finished ? 1 : 0)), quote: ch === Chars.SingleQuote ? 'single' : 'double', start, end: scanner.pos }; } } /** * Consumes a color token from given string */ // a hex color can be followed by `.num` alpha value scanner.start = scanner.pos; if (scanner.eat(Chars.Dot)) { if (scanner.eatWhile(isNumber)) { alpha = scanner.current(); } else { throw scanner.error('Unexpected character for alpha value of color'); } } const { r, g, b, a } = parseColor(color, alpha); const valueStart = scanner.pos; let color = ''; let alpha = ''; if (scanner.eatWhile(isHex)) { color = scanner.substring(valueStart, scanner.pos); alpha = colorAlpha(scanner); } else if (scanner.eat(Chars.Transparent)) { color = '0'; alpha = colorAlpha(scanner) || '0'; } else { alpha = colorAlpha(scanner); } if (color || alpha || scanner.eof()) { const { r, g, b, a } = parseColor(color, alpha); return { type: 'ColorValue', r, g, b, a, raw: scanner.substring(start + 1, scanner.pos), start, end: scanner.pos }; } else { // Consumed # but no actual value: invalid color value, treat it as literal return createLiteral(scanner, start); } } scanner.pos = start; } /** * Consumes alpha value of color: `.1` */ function colorAlpha(scanner: Scanner): string { const start = scanner.pos; if (scanner.eat(Chars.Dot)) { scanner.start = start; if (scanner.eatWhile(isNumber)) { return scanner.current(); } return '1'; } return ''; } /** * Consumes white space characters as string literal from given scanner */ function whiteSpace(scanner: Scanner): WhiteSpace | undefined { const start = scanner.pos; if (scanner.eatWhile(isSpace)) { return { type: 'WhiteSpace', start, end: scanner.pos }; } } /** * Consumes bracket from given scanner */ function bracket(scanner: Scanner): Bracket | undefined { const ch = scanner.peek(); if (isBracket(ch)) { return { type: 'Bracket', open: ch === Chars.RoundBracketOpen, start: scanner.pos++, end: scanner.pos }; } } /** * Consumes operator from given scanner */ function operator(scanner: Scanner): Operator | undefined { const op = operatorType(scanner.peek()); if (op) { return { type: 'Operator', operator: op, start: scanner.pos++, end: scanner.pos }; } } /** * Eats number value from given stream * @return Returns `true` if number was consumed */ function consumeNumber(stream: Scanner): boolean { const start = stream.pos; stream.eat(Chars.Dash); const afterNegative = stream.pos; const hasDecimal = stream.eatWhile(isNumber); const prevPos = stream.pos; if (stream.eat(Chars.Dot)) { // It’s perfectly valid to have numbers like `1.`, which enforces // value to float unit type const hasFloat = stream.eatWhile(isNumber); if (!hasDecimal && !hasFloat) { // Lone dot stream.pos = prevPos; } } // Edge case: consumed dash only: not a number, bail-out if (stream.pos === afterNegative) { stream.pos = start; } return stream.pos !== start; } function isIdentPrefix(code: number): boolean { return code === Chars.At || code === Chars.Dollar; } /** * If given character is an operator, returns it’s type */ function operatorType(ch: number): OperatorType | undefined { return (ch === Chars.Sibling && OperatorType.Sibling) || (ch === Chars.Excl && OperatorType.Important) || (ch === Chars.Comma && OperatorType.ArgumentDelimiter) || (ch === Chars.Colon && OperatorType.PropertyDelimiter) || (ch === Chars.Dash && OperatorType.ValueDelimiter) || void 0; } /** * Check if given code is a hex value (/0-9a-f/) */ function isHex(code: number): boolean { return isNumber(code) || isAlpha(code, 65, 70); // A-F } function isKeyword(code: number): boolean { return isAlphaNumericWord(code) || code === Chars.Dash; } function isBracket(code: number) { return code === Chars.RoundBracketOpen || code === Chars.RoundBracketClose; } function isLiteral(code: number) { return isAlphaWord(code) || code === Chars.Percent || code === Chars.Slash; } /** * Parses given color value from abbreviation into RGBA format */ function parseColor(value: string, alpha?: string): { r: number, g: number, b: number, a: number } { let r = '0'; let g = '0'; let b = '0'; let a = Number(alpha != null && alpha !== '' ? alpha : 1); if (value === 't') { a = 0; } else { switch (value.length) { case 0: break; case 1: r = g = b = value + value; break; case 2: r = g = b = value; break; case 3: r = value[0] + value[0]; g = value[1] + value[1]; b = value[2] + value[2]; break; default: value += value; r = value.slice(0, 2); g = value.slice(2, 4); b = value.slice(4, 6); } } return { r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), a }; } /** * Check if scanner reader must consume dash after given token. * Used in cases where user must explicitly separate numeric values */ function shouldConsumeDashAfter(token: AllTokens): boolean { return token.type === 'ColorValue' || (token.type === 'NumberValue' && !token.unit); } /** * Merges last adjacent tokens into a single literal. * This function is used to overcome edge case when function name was parsed * as a list of separate tokens. For example, a `scale3d()` value will be * parsed as literal and number tokens (`scale` and `3d`) which is a perfectly * valid abbreviation but undesired result. This function will detect last adjacent * literal and number values and combine them into single literal */ function mergeTokens(scanner: Scanner, tokens: AllTokens[]) { let start = 0; let end = 0; while (tokens.length) { const token = last(tokens)!; if (token.type === 'Literal' || token.type === 'NumberValue') { start = token.start!; if (!end) { end = token.end!; } tokens.pop(); } else { break; } } if (start !== end) { tokens.push(createLiteral(scanner, start, end)); } } function last<T>(arr: T[]): T | undefined { return arr[arr.length - 1]; } <MSG> [stylesheet] Do not throw error on empty alpha color value <DFF> @@ -216,12 +216,8 @@ function colorValue(scanner: Scanner): ColorValue | undefined { // a hex color can be followed by `.num` alpha value scanner.start = scanner.pos; - if (scanner.eat(Chars.Dot)) { - if (scanner.eatWhile(isNumber)) { - alpha = scanner.current(); - } else { - throw scanner.error('Unexpected character for alpha value of color'); - } + if (scanner.eat(Chars.Dot) && scanner.eatWhile(isNumber)) { + alpha = scanner.current(); } const { r, g, b, a } = parseColor(color, alpha);
2
[stylesheet] Do not throw error on empty alpha color value
6
.ts
ts
mit
emmetio/emmet
10071976
<NME> setup.py <BEF> ADDFILE <MSG> Added proper structure <DFF> @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import os +import codecs + +try: + from setuptools import setup, find_packages +except ImportError: + from ez_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + +setup( + name='chishop', + version=__import__('chishop').__version__, + description='Simple PyPI server written in Django.', + author='Ask Solem', + author_email='askh@opera.com', + packages=[], + install_requires=[ + 'django>=1.0', + ], + classifiers=[ + "Development Status :: 3 - Alpha", + "Environment :: Web Environment", + "Framework :: Django", + "Operating System :: OS Independent", + "Intended Audience :: Developers", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: BSD License", + "Programming Language :: Python", + ], + long_description=codecs.open('README', "r", "utf-8").read(), +)
34
Added proper structure
0
.py
py
bsd-3-clause
ask/chishop
10071977
<NME> index.erb <BEF> <h1>Split Dashboard</h1> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <% @experiments.each do |experiment| %> <h2><%= experiment.name %></h2> <table class="queues"> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <th>Z-Score</th> <th>Winner</th> </tr> <% total_participants = total_completed = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td><%= alternative.name %></td> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= alternative.name %>'> <input type="submit" value="Use this"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_completed += alternative.completed_count %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_participants - total_completed %></td> <td><%= total_completed %></td> <td>N/A</td> <td>N/A</td> <td>N/A</td> </tr> </table> <% end %> <MSG> More helpful text when no experiments exist <DFF> @@ -1,56 +1,61 @@ <h1>Split Dashboard</h1> -<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> +<% if @experiments.any? %> + <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> -<% @experiments.each do |experiment| %> - <h2><%= experiment.name %></h2> - <table class="queues"> - <tr> - <th>Alternative Name</th> - <th>Participants</th> - <th>Non-finished</th> - <th>Completed</th> - <th>Conversion Rate</th> - <th>Z-Score</th> - <th>Winner</th> - </tr> - - <% total_participants = total_completed = 0 %> - <% experiment.alternatives.each do |alternative| %> + <% @experiments.each do |experiment| %> + <h2><%= experiment.name %></h2> + <table class="queues"> <tr> - <td><%= alternative.name %></td> - <td><%= alternative.participant_count %></td> - <td><%= alternative.participant_count - alternative.completed_count %></td> - <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> - <td> - <% if experiment.winner %> - <% if experiment.winner.name == alternative.name %> - Winner + <th>Alternative Name</th> + <th>Participants</th> + <th>Non-finished</th> + <th>Completed</th> + <th>Conversion Rate</th> + <th>Z-Score</th> + <th>Winner</th> + </tr> + + <% total_participants = total_completed = 0 %> + <% experiment.alternatives.each do |alternative| %> + <tr> + <td><%= alternative.name %></td> + <td><%= alternative.participant_count %></td> + <td><%= alternative.participant_count - alternative.completed_count %></td> + <td><%= alternative.completed_count %></td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> + <td><%= alternative.z_score %></td> + <td> + <% if experiment.winner %> + <% if experiment.winner.name == alternative.name %> + Winner + <% else %> + Loser + <% end %> <% else %> - Loser + <form action="<%= url experiment.name %>" method='post'> + <input type='hidden' name='alternative' value='<%= alternative.name %>'> + <input type="submit" value="Use this"> + </form> <% end %> - <% else %> - <form action="<%= url experiment.name %>" method='post'> - <input type='hidden' name='alternative' value='<%= alternative.name %>'> - <input type="submit" value="Use this"> - </form> - <% end %> - </td> - </tr> + </td> + </tr> - <% total_participants += alternative.participant_count %> - <% total_completed += alternative.completed_count %> - <% end %> + <% total_participants += alternative.participant_count %> + <% total_completed += alternative.completed_count %> + <% end %> - <tr class="totals"> - <td>Totals</td> - <td><%= total_participants %></td> - <td><%= total_participants - total_completed %></td> - <td><%= total_completed %></td> - <td>N/A</td> - <td>N/A</td> - <td>N/A</td> - </tr> - </table> + <tr class="totals"> + <td>Totals</td> + <td><%= total_participants %></td> + <td><%= total_participants - total_completed %></td> + <td><%= total_completed %></td> + <td>N/A</td> + <td>N/A</td> + <td>N/A</td> + </tr> + </table> + <% end %> +<% else %> + <p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p> + <p class="intro">Check out the <a href='https://github.com/andrew/split#readme'>Readme</a> for more help getting started.</p> <% end %> \ No newline at end of file
53
More helpful text when no experiments exist
48
.erb
erb
mit
splitrb/split
10071978
<NME> index.erb <BEF> <h1>Split Dashboard</h1> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <% @experiments.each do |experiment| %> <h2><%= experiment.name %></h2> <table class="queues"> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <th>Z-Score</th> <th>Winner</th> </tr> <% total_participants = total_completed = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td><%= alternative.name %></td> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= alternative.name %>'> <input type="submit" value="Use this"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_completed += alternative.completed_count %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_participants - total_completed %></td> <td><%= total_completed %></td> <td>N/A</td> <td>N/A</td> <td>N/A</td> </tr> </table> <% end %> <MSG> More helpful text when no experiments exist <DFF> @@ -1,56 +1,61 @@ <h1>Split Dashboard</h1> -<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> +<% if @experiments.any? %> + <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> -<% @experiments.each do |experiment| %> - <h2><%= experiment.name %></h2> - <table class="queues"> - <tr> - <th>Alternative Name</th> - <th>Participants</th> - <th>Non-finished</th> - <th>Completed</th> - <th>Conversion Rate</th> - <th>Z-Score</th> - <th>Winner</th> - </tr> - - <% total_participants = total_completed = 0 %> - <% experiment.alternatives.each do |alternative| %> + <% @experiments.each do |experiment| %> + <h2><%= experiment.name %></h2> + <table class="queues"> <tr> - <td><%= alternative.name %></td> - <td><%= alternative.participant_count %></td> - <td><%= alternative.participant_count - alternative.completed_count %></td> - <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> - <td> - <% if experiment.winner %> - <% if experiment.winner.name == alternative.name %> - Winner + <th>Alternative Name</th> + <th>Participants</th> + <th>Non-finished</th> + <th>Completed</th> + <th>Conversion Rate</th> + <th>Z-Score</th> + <th>Winner</th> + </tr> + + <% total_participants = total_completed = 0 %> + <% experiment.alternatives.each do |alternative| %> + <tr> + <td><%= alternative.name %></td> + <td><%= alternative.participant_count %></td> + <td><%= alternative.participant_count - alternative.completed_count %></td> + <td><%= alternative.completed_count %></td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> + <td><%= alternative.z_score %></td> + <td> + <% if experiment.winner %> + <% if experiment.winner.name == alternative.name %> + Winner + <% else %> + Loser + <% end %> <% else %> - Loser + <form action="<%= url experiment.name %>" method='post'> + <input type='hidden' name='alternative' value='<%= alternative.name %>'> + <input type="submit" value="Use this"> + </form> <% end %> - <% else %> - <form action="<%= url experiment.name %>" method='post'> - <input type='hidden' name='alternative' value='<%= alternative.name %>'> - <input type="submit" value="Use this"> - </form> - <% end %> - </td> - </tr> + </td> + </tr> - <% total_participants += alternative.participant_count %> - <% total_completed += alternative.completed_count %> - <% end %> + <% total_participants += alternative.participant_count %> + <% total_completed += alternative.completed_count %> + <% end %> - <tr class="totals"> - <td>Totals</td> - <td><%= total_participants %></td> - <td><%= total_participants - total_completed %></td> - <td><%= total_completed %></td> - <td>N/A</td> - <td>N/A</td> - <td>N/A</td> - </tr> - </table> + <tr class="totals"> + <td>Totals</td> + <td><%= total_participants %></td> + <td><%= total_participants - total_completed %></td> + <td><%= total_completed %></td> + <td>N/A</td> + <td>N/A</td> + <td>N/A</td> + </tr> + </table> + <% end %> +<% else %> + <p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p> + <p class="intro">Check out the <a href='https://github.com/andrew/split#readme'>Readme</a> for more help getting started.</p> <% end %> \ No newline at end of file
53
More helpful text when no experiments exist
48
.erb
erb
mit
splitrb/split
10071979
<NME> index.erb <BEF> <h1>Split Dashboard</h1> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <% @experiments.each do |experiment| %> <h2><%= experiment.name %></h2> <table class="queues"> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <th>Z-Score</th> <th>Winner</th> </tr> <% total_participants = total_completed = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td><%= alternative.name %></td> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= alternative.name %>'> <input type="submit" value="Use this"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_completed += alternative.completed_count %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_participants - total_completed %></td> <td><%= total_completed %></td> <td>N/A</td> <td>N/A</td> <td>N/A</td> </tr> </table> <% end %> <MSG> More helpful text when no experiments exist <DFF> @@ -1,56 +1,61 @@ <h1>Split Dashboard</h1> -<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> +<% if @experiments.any? %> + <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> -<% @experiments.each do |experiment| %> - <h2><%= experiment.name %></h2> - <table class="queues"> - <tr> - <th>Alternative Name</th> - <th>Participants</th> - <th>Non-finished</th> - <th>Completed</th> - <th>Conversion Rate</th> - <th>Z-Score</th> - <th>Winner</th> - </tr> - - <% total_participants = total_completed = 0 %> - <% experiment.alternatives.each do |alternative| %> + <% @experiments.each do |experiment| %> + <h2><%= experiment.name %></h2> + <table class="queues"> <tr> - <td><%= alternative.name %></td> - <td><%= alternative.participant_count %></td> - <td><%= alternative.participant_count - alternative.completed_count %></td> - <td><%= alternative.completed_count %></td> - <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> - <td><%= alternative.z_score %></td> - <td> - <% if experiment.winner %> - <% if experiment.winner.name == alternative.name %> - Winner + <th>Alternative Name</th> + <th>Participants</th> + <th>Non-finished</th> + <th>Completed</th> + <th>Conversion Rate</th> + <th>Z-Score</th> + <th>Winner</th> + </tr> + + <% total_participants = total_completed = 0 %> + <% experiment.alternatives.each do |alternative| %> + <tr> + <td><%= alternative.name %></td> + <td><%= alternative.participant_count %></td> + <td><%= alternative.participant_count - alternative.completed_count %></td> + <td><%= alternative.completed_count %></td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> + <td><%= alternative.z_score %></td> + <td> + <% if experiment.winner %> + <% if experiment.winner.name == alternative.name %> + Winner + <% else %> + Loser + <% end %> <% else %> - Loser + <form action="<%= url experiment.name %>" method='post'> + <input type='hidden' name='alternative' value='<%= alternative.name %>'> + <input type="submit" value="Use this"> + </form> <% end %> - <% else %> - <form action="<%= url experiment.name %>" method='post'> - <input type='hidden' name='alternative' value='<%= alternative.name %>'> - <input type="submit" value="Use this"> - </form> - <% end %> - </td> - </tr> + </td> + </tr> - <% total_participants += alternative.participant_count %> - <% total_completed += alternative.completed_count %> - <% end %> + <% total_participants += alternative.participant_count %> + <% total_completed += alternative.completed_count %> + <% end %> - <tr class="totals"> - <td>Totals</td> - <td><%= total_participants %></td> - <td><%= total_participants - total_completed %></td> - <td><%= total_completed %></td> - <td>N/A</td> - <td>N/A</td> - <td>N/A</td> - </tr> - </table> + <tr class="totals"> + <td>Totals</td> + <td><%= total_participants %></td> + <td><%= total_participants - total_completed %></td> + <td><%= total_completed %></td> + <td>N/A</td> + <td>N/A</td> + <td>N/A</td> + </tr> + </table> + <% end %> +<% else %> + <p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p> + <p class="intro">Check out the <a href='https://github.com/andrew/split#readme'>Readme</a> for more help getting started.</p> <% end %> \ No newline at end of file
53
More helpful text when no experiments exist
48
.erb
erb
mit
splitrb/split
10071980
<NME> _experiment.erb <BEF> <div class="experiment"> <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> <div class='inline-controls'> <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> <input type="submit" value="Reset Data"> </form> <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> <input type="hidden" name="_method" value="delete"/> <input type="submit" value="Delete" class="red"> </form> </div> <table> <tr> summary_texts = {} extra_columns.each do |column| extra_infos = experiment.alternatives.map(&:extra_info).select{|extra_info| extra_info && extra_info[column] } if extra_infos[0][column].kind_of?(Numeric) summary_texts[column] = extra_infos.inject(0){|sum, extra_info| sum += extra_info[column]} else summary_texts[column] = "N/A" end end %> <div class="<%= experiment_class %>" data-name="<%= experiment.name %>" data-complete="<%= experiment.has_winner? %>"> <div class="experiment-header"> <h2> Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %> <% unless goal.nil? %><span class='goal'>Goal:<%= goal %></span><% end %> <% metrics = @metrics.select {|metric| metric.experiments.include? experiment} %> <% unless metrics.empty? %> <span class='goal'>Metrics:<%= metrics.map(&:name).join(', ') %></span> <% end %> </h2> <% if goal.nil? %> <div class='inline-controls'> <small><%= experiment.start_time ? experiment.start_time.strftime('%Y-%m-%d') : 'Unknown' %></small> <%= erb :_controls, :locals => {:experiment => experiment} %> </div> <% end %> </div> <table> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <% extra_columns.each do |column| %> <th><%= column %></th> <% end %> <th> <form> <select id="dropdown-<%=experiment.jstring(goal)%>" name="dropdown-<%=experiment.jstring(goal)%>"> <option value="confidence-<%=experiment.jstring(goal)%>">Confidence</option> <option value="probability-<%=experiment.jstring(goal)%>">Probability of being Winner</option> </select> </form> </th> <th>Finish</th> </tr> <% total_participants = total_completed = total_unfinished = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td> <%= alternative.name %> <% if alternative.control? %> <em>control</em> <% end %> <form action="<%= url('force_alternative') + '?experiment=' + experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Force for current user" class="green"> </form> </td> <td><%= alternative.participant_count %></td> <td><%= alternative.unfinished_count %></td> <td><%= alternative.completed_count(goal) %></td> <td> <%= number_to_percentage(alternative.conversion_rate(goal)) %>% <% if experiment.control.conversion_rate(goal) > 0 && !alternative.control? %> <% if alternative.conversion_rate(goal) > experiment.control.conversion_rate(goal) %> <span class='better'> +<%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% elsif alternative.conversion_rate(goal) < experiment.control.conversion_rate(goal) %> <span class='worse'> <%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% end %> <% end %> </td> <script type="text/javascript" id="sourcecode"> $(document).ready(function(){ $('.probability-<%=experiment.jstring(goal)%>').hide(); $('#dropdown-<%=experiment.jstring(goal)%>').change(function() { $('.box-<%=experiment.jstring(goal)%>').hide(); $('.' + $(this).val()).show(); }); }); </script> <% extra_columns.each do |column| %> <td><%= alternative.extra_info && alternative.extra_info[column] %></td> <% end %> <td> <div class="box-<%=experiment.jstring(goal)%> confidence-<%=experiment.jstring(goal)%>"> <span title='z-score: <%= round(alternative.z_score(goal), 3) %>'><%= confidence_level(alternative.z_score(goal)) %></span> <br> </div> <div class="box-<%=experiment.jstring(goal)%> probability-<%=experiment.jstring(goal)%>"> <span title="p_winner: <%= round(alternative.p_winner(goal), 3) %>"><%= number_to_percentage(round(alternative.p_winner(goal), 3)) %>%</span> </div> </td> <td> <% if experiment.has_winner? %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url('experiment') + '?experiment=' + experiment.name %>" method='post' onclick="return confirmWinner()"> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Use this" class="green"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_unfinished += alternative.unfinished_count %> <% total_completed += alternative.completed_count(goal) %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_unfinished %></td> <td><%= total_completed %></td> <td>N/A</td> <% extra_columns.each do |column| %> <td> <%= summary_texts[column] %> </td> <% end %> <td>N/A</td> <td>N/A</td> </tr> </table> </div> <MSG> Experiment header <DFF> @@ -1,13 +1,15 @@ <div class="experiment"> - <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> - <div class='inline-controls'> - <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> - <input type="submit" value="Reset Data"> - </form> - <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> - <input type="hidden" name="_method" value="delete"/> - <input type="submit" value="Delete" class="red"> - </form> + <div class="experiment-header"> + <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> + <div class='inline-controls'> + <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> + <input type="submit" value="Reset Data"> + </form> + <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> + <input type="hidden" name="_method" value="delete"/> + <input type="submit" value="Delete" class="red"> + </form> + </div> </div> <table> <tr>
11
Experiment header
9
.erb
erb
mit
splitrb/split
10071981
<NME> _experiment.erb <BEF> <div class="experiment"> <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> <div class='inline-controls'> <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> <input type="submit" value="Reset Data"> </form> <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> <input type="hidden" name="_method" value="delete"/> <input type="submit" value="Delete" class="red"> </form> </div> <table> <tr> summary_texts = {} extra_columns.each do |column| extra_infos = experiment.alternatives.map(&:extra_info).select{|extra_info| extra_info && extra_info[column] } if extra_infos[0][column].kind_of?(Numeric) summary_texts[column] = extra_infos.inject(0){|sum, extra_info| sum += extra_info[column]} else summary_texts[column] = "N/A" end end %> <div class="<%= experiment_class %>" data-name="<%= experiment.name %>" data-complete="<%= experiment.has_winner? %>"> <div class="experiment-header"> <h2> Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %> <% unless goal.nil? %><span class='goal'>Goal:<%= goal %></span><% end %> <% metrics = @metrics.select {|metric| metric.experiments.include? experiment} %> <% unless metrics.empty? %> <span class='goal'>Metrics:<%= metrics.map(&:name).join(', ') %></span> <% end %> </h2> <% if goal.nil? %> <div class='inline-controls'> <small><%= experiment.start_time ? experiment.start_time.strftime('%Y-%m-%d') : 'Unknown' %></small> <%= erb :_controls, :locals => {:experiment => experiment} %> </div> <% end %> </div> <table> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <% extra_columns.each do |column| %> <th><%= column %></th> <% end %> <th> <form> <select id="dropdown-<%=experiment.jstring(goal)%>" name="dropdown-<%=experiment.jstring(goal)%>"> <option value="confidence-<%=experiment.jstring(goal)%>">Confidence</option> <option value="probability-<%=experiment.jstring(goal)%>">Probability of being Winner</option> </select> </form> </th> <th>Finish</th> </tr> <% total_participants = total_completed = total_unfinished = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td> <%= alternative.name %> <% if alternative.control? %> <em>control</em> <% end %> <form action="<%= url('force_alternative') + '?experiment=' + experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Force for current user" class="green"> </form> </td> <td><%= alternative.participant_count %></td> <td><%= alternative.unfinished_count %></td> <td><%= alternative.completed_count(goal) %></td> <td> <%= number_to_percentage(alternative.conversion_rate(goal)) %>% <% if experiment.control.conversion_rate(goal) > 0 && !alternative.control? %> <% if alternative.conversion_rate(goal) > experiment.control.conversion_rate(goal) %> <span class='better'> +<%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% elsif alternative.conversion_rate(goal) < experiment.control.conversion_rate(goal) %> <span class='worse'> <%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% end %> <% end %> </td> <script type="text/javascript" id="sourcecode"> $(document).ready(function(){ $('.probability-<%=experiment.jstring(goal)%>').hide(); $('#dropdown-<%=experiment.jstring(goal)%>').change(function() { $('.box-<%=experiment.jstring(goal)%>').hide(); $('.' + $(this).val()).show(); }); }); </script> <% extra_columns.each do |column| %> <td><%= alternative.extra_info && alternative.extra_info[column] %></td> <% end %> <td> <div class="box-<%=experiment.jstring(goal)%> confidence-<%=experiment.jstring(goal)%>"> <span title='z-score: <%= round(alternative.z_score(goal), 3) %>'><%= confidence_level(alternative.z_score(goal)) %></span> <br> </div> <div class="box-<%=experiment.jstring(goal)%> probability-<%=experiment.jstring(goal)%>"> <span title="p_winner: <%= round(alternative.p_winner(goal), 3) %>"><%= number_to_percentage(round(alternative.p_winner(goal), 3)) %>%</span> </div> </td> <td> <% if experiment.has_winner? %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url('experiment') + '?experiment=' + experiment.name %>" method='post' onclick="return confirmWinner()"> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Use this" class="green"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_unfinished += alternative.unfinished_count %> <% total_completed += alternative.completed_count(goal) %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_unfinished %></td> <td><%= total_completed %></td> <td>N/A</td> <% extra_columns.each do |column| %> <td> <%= summary_texts[column] %> </td> <% end %> <td>N/A</td> <td>N/A</td> </tr> </table> </div> <MSG> Experiment header <DFF> @@ -1,13 +1,15 @@ <div class="experiment"> - <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> - <div class='inline-controls'> - <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> - <input type="submit" value="Reset Data"> - </form> - <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> - <input type="hidden" name="_method" value="delete"/> - <input type="submit" value="Delete" class="red"> - </form> + <div class="experiment-header"> + <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> + <div class='inline-controls'> + <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> + <input type="submit" value="Reset Data"> + </form> + <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> + <input type="hidden" name="_method" value="delete"/> + <input type="submit" value="Delete" class="red"> + </form> + </div> </div> <table> <tr>
11
Experiment header
9
.erb
erb
mit
splitrb/split
10071982
<NME> _experiment.erb <BEF> <div class="experiment"> <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> <div class='inline-controls'> <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> <input type="submit" value="Reset Data"> </form> <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> <input type="hidden" name="_method" value="delete"/> <input type="submit" value="Delete" class="red"> </form> </div> <table> <tr> summary_texts = {} extra_columns.each do |column| extra_infos = experiment.alternatives.map(&:extra_info).select{|extra_info| extra_info && extra_info[column] } if extra_infos[0][column].kind_of?(Numeric) summary_texts[column] = extra_infos.inject(0){|sum, extra_info| sum += extra_info[column]} else summary_texts[column] = "N/A" end end %> <div class="<%= experiment_class %>" data-name="<%= experiment.name %>" data-complete="<%= experiment.has_winner? %>"> <div class="experiment-header"> <h2> Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %> <% unless goal.nil? %><span class='goal'>Goal:<%= goal %></span><% end %> <% metrics = @metrics.select {|metric| metric.experiments.include? experiment} %> <% unless metrics.empty? %> <span class='goal'>Metrics:<%= metrics.map(&:name).join(', ') %></span> <% end %> </h2> <% if goal.nil? %> <div class='inline-controls'> <small><%= experiment.start_time ? experiment.start_time.strftime('%Y-%m-%d') : 'Unknown' %></small> <%= erb :_controls, :locals => {:experiment => experiment} %> </div> <% end %> </div> <table> <tr> <th>Alternative Name</th> <th>Participants</th> <th>Non-finished</th> <th>Completed</th> <th>Conversion Rate</th> <% extra_columns.each do |column| %> <th><%= column %></th> <% end %> <th> <form> <select id="dropdown-<%=experiment.jstring(goal)%>" name="dropdown-<%=experiment.jstring(goal)%>"> <option value="confidence-<%=experiment.jstring(goal)%>">Confidence</option> <option value="probability-<%=experiment.jstring(goal)%>">Probability of being Winner</option> </select> </form> </th> <th>Finish</th> </tr> <% total_participants = total_completed = total_unfinished = 0 %> <% experiment.alternatives.each do |alternative| %> <tr> <td> <%= alternative.name %> <% if alternative.control? %> <em>control</em> <% end %> <form action="<%= url('force_alternative') + '?experiment=' + experiment.name %>" method='post'> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Force for current user" class="green"> </form> </td> <td><%= alternative.participant_count %></td> <td><%= alternative.unfinished_count %></td> <td><%= alternative.completed_count(goal) %></td> <td> <%= number_to_percentage(alternative.conversion_rate(goal)) %>% <% if experiment.control.conversion_rate(goal) > 0 && !alternative.control? %> <% if alternative.conversion_rate(goal) > experiment.control.conversion_rate(goal) %> <span class='better'> +<%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% elsif alternative.conversion_rate(goal) < experiment.control.conversion_rate(goal) %> <span class='worse'> <%= number_to_percentage((alternative.conversion_rate(goal)/experiment.control.conversion_rate(goal))-1) %>% </span> <% end %> <% end %> </td> <script type="text/javascript" id="sourcecode"> $(document).ready(function(){ $('.probability-<%=experiment.jstring(goal)%>').hide(); $('#dropdown-<%=experiment.jstring(goal)%>').change(function() { $('.box-<%=experiment.jstring(goal)%>').hide(); $('.' + $(this).val()).show(); }); }); </script> <% extra_columns.each do |column| %> <td><%= alternative.extra_info && alternative.extra_info[column] %></td> <% end %> <td> <div class="box-<%=experiment.jstring(goal)%> confidence-<%=experiment.jstring(goal)%>"> <span title='z-score: <%= round(alternative.z_score(goal), 3) %>'><%= confidence_level(alternative.z_score(goal)) %></span> <br> </div> <div class="box-<%=experiment.jstring(goal)%> probability-<%=experiment.jstring(goal)%>"> <span title="p_winner: <%= round(alternative.p_winner(goal), 3) %>"><%= number_to_percentage(round(alternative.p_winner(goal), 3)) %>%</span> </div> </td> <td> <% if experiment.has_winner? %> <% if experiment.winner.name == alternative.name %> Winner <% else %> Loser <% end %> <% else %> <form action="<%= url('experiment') + '?experiment=' + experiment.name %>" method='post' onclick="return confirmWinner()"> <input type='hidden' name='alternative' value='<%= h alternative.name %>'> <input type="submit" value="Use this" class="green"> </form> <% end %> </td> </tr> <% total_participants += alternative.participant_count %> <% total_unfinished += alternative.unfinished_count %> <% total_completed += alternative.completed_count(goal) %> <% end %> <tr class="totals"> <td>Totals</td> <td><%= total_participants %></td> <td><%= total_unfinished %></td> <td><%= total_completed %></td> <td>N/A</td> <% extra_columns.each do |column| %> <td> <%= summary_texts[column] %> </td> <% end %> <td>N/A</td> <td>N/A</td> </tr> </table> </div> <MSG> Experiment header <DFF> @@ -1,13 +1,15 @@ <div class="experiment"> - <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> - <div class='inline-controls'> - <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> - <input type="submit" value="Reset Data"> - </form> - <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> - <input type="hidden" name="_method" value="delete"/> - <input type="submit" value="Delete" class="red"> - </form> + <div class="experiment-header"> + <h2>Experiment: <%= experiment.name %> <% if experiment.version > 1 %><span class='version'>v<%= experiment.version %></span><% end %></h2> + <div class='inline-controls'> + <form action="<%= url "/reset/#{experiment.name}" %>" method='post' onclick="return confirmReset()"> + <input type="submit" value="Reset Data"> + </form> + <form action="<%= url "/#{experiment.name}" %>" method='post' onclick="return confirmDelete()"> + <input type="hidden" name="_method" value="delete"/> + <input type="submit" value="Delete" class="red"> + </form> + </div> </div> <table> <tr>
11
Experiment header
9
.erb
erb
mit
splitrb/split
10071983
<NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex def bots @bots ||= { # Indexers "AdsBot-Google" => "Google Adwords", "Baidu" => "Chinese search engine", "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander', "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Blocked a few more common bot user agents (#485) <DFF> @@ -48,7 +48,9 @@ module Split 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', + 'YandexAccessibilityBot' => 'Yandex accessibility spider', 'YandexBot' => 'Yandex spider', + 'YandexMobileBot' => 'Yandex mobile spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries @@ -73,10 +75,13 @@ module Split 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', + 'LinkedInBot' => 'LinkedIn bot', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', + 'Pinterest' => 'Pinterest Bot', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', + 'Slackbot' => 'Slackbot link expander', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander',
5
Blocked a few more common bot user agents (#485)
0
.rb
rb
mit
splitrb/split
10071984
<NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex def bots @bots ||= { # Indexers "AdsBot-Google" => "Google Adwords", "Baidu" => "Chinese search engine", "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander', "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Blocked a few more common bot user agents (#485) <DFF> @@ -48,7 +48,9 @@ module Split 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', + 'YandexAccessibilityBot' => 'Yandex accessibility spider', 'YandexBot' => 'Yandex spider', + 'YandexMobileBot' => 'Yandex mobile spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries @@ -73,10 +75,13 @@ module Split 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', + 'LinkedInBot' => 'LinkedIn bot', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', + 'Pinterest' => 'Pinterest Bot', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', + 'Slackbot' => 'Slackbot link expander', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander',
5
Blocked a few more common bot user agents (#485)
0
.rb
rb
mit
splitrb/split
10071985
<NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex def bots @bots ||= { # Indexers "AdsBot-Google" => "Google Adwords", "Baidu" => "Chinese search engine", "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander', "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Blocked a few more common bot user agents (#485) <DFF> @@ -48,7 +48,9 @@ module Split 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', + 'YandexAccessibilityBot' => 'Yandex accessibility spider', 'YandexBot' => 'Yandex spider', + 'YandexMobileBot' => 'Yandex mobile spider', 'ZIBB' => 'ZIBB spider', # HTTP libraries @@ -73,10 +75,13 @@ module Split 'facebookexternalhit' => 'facebook bot', 'Feedfetcher-Google' => 'Google Feedfetcher', 'https://developers.google.com/+/web/snippet' => 'Google+ Snippet Fetcher', + 'LinkedInBot' => 'LinkedIn bot', 'LongURL' => 'URL expander service', 'NING' => 'NING - Yet Another Twitter Swarmer', + 'Pinterest' => 'Pinterest Bot', 'redditbot' => 'Reddit Bot', 'ShortLinkTranslate' => 'Link shortener', + 'Slackbot' => 'Slackbot link expander', 'TweetmemeBot' => 'TweetMeMe Crawler', 'Twitterbot' => 'Twitter URL expander', 'UnwindFetch' => 'Gnip URL expander',
5
Blocked a few more common bot user agents (#485)
0
.rb
rb
mit
splitrb/split
10071986
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do let(:context) { double(lookup: "blah") } subject { Split::Persistence::RedisAdapter.new(context) } describe "#redis_key" do before { Split::Persistence::RedisAdapter.reset_config! } context "default" do it "should raise error with prompt to set lookup_by" do expect { Split::Persistence::RedisAdapter.new(context) }.to raise_error(RuntimeError) end end context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context "config with lookup_by = proc { |context| context.test }" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "block" }) } let(:context) { double(test: "block") } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context 'config with lookup_by = "method_name"' do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "method_name") } let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Allow RedisAdapter to be used outside of a session context <DFF> @@ -16,6 +16,15 @@ describe Split::Persistence::RedisAdapter do end end + context 'config with key' do + before { Split::Persistence::RedisAdapter.reset_config! } + subject { Split::Persistence::RedisAdapter.new(context, 'manual') } + + it 'should be "persistence:manual"' do + expect(subject.redis_key).to eq('persistence:manual') + end + end + context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) }
9
Allow RedisAdapter to be used outside of a session context
0
.rb
rb
mit
splitrb/split
10071987
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do let(:context) { double(lookup: "blah") } subject { Split::Persistence::RedisAdapter.new(context) } describe "#redis_key" do before { Split::Persistence::RedisAdapter.reset_config! } context "default" do it "should raise error with prompt to set lookup_by" do expect { Split::Persistence::RedisAdapter.new(context) }.to raise_error(RuntimeError) end end context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context "config with lookup_by = proc { |context| context.test }" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "block" }) } let(:context) { double(test: "block") } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context 'config with lookup_by = "method_name"' do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "method_name") } let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Allow RedisAdapter to be used outside of a session context <DFF> @@ -16,6 +16,15 @@ describe Split::Persistence::RedisAdapter do end end + context 'config with key' do + before { Split::Persistence::RedisAdapter.reset_config! } + subject { Split::Persistence::RedisAdapter.new(context, 'manual') } + + it 'should be "persistence:manual"' do + expect(subject.redis_key).to eq('persistence:manual') + end + end + context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) }
9
Allow RedisAdapter to be used outside of a session context
0
.rb
rb
mit
splitrb/split
10071988
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do let(:context) { double(lookup: "blah") } subject { Split::Persistence::RedisAdapter.new(context) } describe "#redis_key" do before { Split::Persistence::RedisAdapter.reset_config! } context "default" do it "should raise error with prompt to set lookup_by" do expect { Split::Persistence::RedisAdapter.new(context) }.to raise_error(RuntimeError) end end context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context "config with lookup_by = proc { |context| context.test }" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "block" }) } let(:context) { double(test: "block") } it 'should be "persistence:block"' do expect(subject.redis_key).to eq("persistence:block") end end context 'config with lookup_by = "method_name"' do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "method_name") } let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Allow RedisAdapter to be used outside of a session context <DFF> @@ -16,6 +16,15 @@ describe Split::Persistence::RedisAdapter do end end + context 'config with key' do + before { Split::Persistence::RedisAdapter.reset_config! } + subject { Split::Persistence::RedisAdapter.new(context, 'manual') } + + it 'should be "persistence:manual"' do + expect(subject.redis_key).to eq('persistence:manual') + end + end + context 'config with lookup_by = proc { "block" }' do before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) }
9
Allow RedisAdapter to be used outside of a session context
0
.rb
rb
mit
splitrb/split
10071989
<NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); throws(() => parse('/'), /Unexpected character/); }); }); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); equal(str('foo\\'), '<foo></foo>'); }); it('missing braces', () => { // Do not throw errors on missing closing braces equal(str('div[title="test"'), '<div title="test"></div>'); equal(str('div(foo'), '<div></div>(<foo></foo>)'); equal(str('div{foo'), '<div>foo</div>'); }); }); <MSG> Support JSX component names parsing <DFF> @@ -10,6 +10,7 @@ describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); + equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); @@ -129,4 +130,12 @@ describe('Parser', () => { throws(() => parse('/'), /Unexpected character/); }); + + it('JSX names', () => { + equal(str('foo.bar'), '<foo class=bar></foo>'); + equal(str('Foo.bar'), '<Foo class=bar></Foo>'); + equal(str('Foo.Bar'), '<Foo.Bar></Foo.Bar>'); + equal(str('Foo.Bar.baz'), '<Foo.Bar class=baz></Foo.Bar>'); + equal(str('Foo.Bar.Baz'), '<Foo.Bar.Baz></Foo.Bar.Baz>'); + }); });
9
Support JSX component names parsing
0
.ts
ts
mit
emmetio/emmet
10071990
<NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); throws(() => parse('/'), /Unexpected character/); }); }); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); equal(str('foo\\'), '<foo></foo>'); }); it('missing braces', () => { // Do not throw errors on missing closing braces equal(str('div[title="test"'), '<div title="test"></div>'); equal(str('div(foo'), '<div></div>(<foo></foo>)'); equal(str('div{foo'), '<div>foo</div>'); }); }); <MSG> Support JSX component names parsing <DFF> @@ -10,6 +10,7 @@ describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); + equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); @@ -129,4 +130,12 @@ describe('Parser', () => { throws(() => parse('/'), /Unexpected character/); }); + + it('JSX names', () => { + equal(str('foo.bar'), '<foo class=bar></foo>'); + equal(str('Foo.bar'), '<Foo class=bar></Foo>'); + equal(str('Foo.Bar'), '<Foo.Bar></Foo.Bar>'); + equal(str('Foo.Bar.baz'), '<Foo.Bar class=baz></Foo.Bar>'); + equal(str('Foo.Bar.Baz'), '<Foo.Bar.Baz></Foo.Bar.Baz>'); + }); });
9
Support JSX component names parsing
0
.ts
ts
mit
emmetio/emmet
10071991
<NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["andrewnez@gmail.com"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end end <MSG> Use a real redis-server on CI <DFF> @@ -39,6 +39,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' - s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end
0
Use a real redis-server on CI
1
.gemspec
gemspec
mit
splitrb/split
10071992
<NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["andrewnez@gmail.com"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end end <MSG> Use a real redis-server on CI <DFF> @@ -39,6 +39,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' - s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end
0
Use a real redis-server on CI
1
.gemspec
gemspec
mit
splitrb/split
10071993
<NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["andrewnez@gmail.com"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end end <MSG> Use a real redis-server on CI <DFF> @@ -39,6 +39,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'rake', '~> 13' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'pry', '~> 0.10' - s.add_development_dependency 'fakeredis', '~> 0.7' s.add_development_dependency 'rails', '>= 5.0' end
0
Use a real redis-server on CI
1
.gemspec
gemspec
mit
splitrb/split
10071994
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Remove usage of deprecated implicit block expectation from specs
0
.rb
rb
mit
splitrb/split
10071995
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Remove usage of deprecated implicit block expectation from specs
0
.rb
rb
mit
splitrb/split
10071996
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Remove usage of deprecated implicit block expectation from specs
0
.rb
rb
mit
splitrb/split
10071997
<NME> README.md <BEF> # transducers.js A small library for generalized transformation of data. This provides a bunch of transformation functions that can be applied to any data structure. It is a direct port of Clojure's [transducers](http://blog.cognitect.com/blog/2014/8/6/transducers-are-coming) in JavaScript. Read more in [this post](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data). The algorithm behind this, explained in the above post, not only allows for it to work with any data structure (arrays, objects, iterators, immutable data structures, you name it) but it also provides better performance than other alternatives such as underscore or lodash. This is because there are no intermediate collections. See [this post](http://jlongster.com/Transducers.js-Round-2-with-Benchmarks) for benchmarks. ``` npm install transducers.js ``` For browsers, grab the file `dist/transducers.js`. When writing programs, we frequently write methods that take in collections, do something with them, and return a result. The problem is that we frequently only write these functions to work a specific data structure, so if we ever change our data type or wanted to reuse that functionality, you can't. We need to decouple these kinds of concerns. A transducer is a function that takes a reducing function and returns a new one. It can perform the necessary work and call the original reducing function to move on to the next "step". In this library, a transducer a little more than that (it's actually an object that also supports init and finalizer methods) but generally you don't have to worry about these internal details. Read [my post](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data) if you want to learn more about the algorithm. ```js var transform = compose( map(x => x * 3), filter(x => x % 2 === 0), take(2) ); seq([1, 2, 3, 4, 5], transform); // -> [ 6, 12 ] function* nums() { var i = 1; while(true) { yield i++; } } into([], transform, nums()); // -> [ 6, 12 ] into([], transform, Immutable.Vector(1, 2, 3, 4, 5)) // -> [ 6, 12 ] ``` All of these work with arrays, objects, and any iterable data structure (like [immutable-js](https://github.com/facebook/immutable-js)) and you get all the high performance guarantees for free. The above code always only performs 2 transformations because of `take(2)`, no matter how large the array. This is done without laziness or any overhead of intermediate structures. ## Transformations The following transformations are available, and there are more to come (like `partition`). * `map(coll?, f, ctx?)` &mdash; call `f` on each item * `filter(coll?, f, ctx?)` &mdash; only include the items where the result of calling `f` with the item is truthy * `remove(coll?, f, ctx?)` &mdash; only include the items where the result of calling `f` with the item is falsy * `keep(coll?)` &mdash; remove all items that are `null` or `undefined` * `take(coll?, n)` &mdash; grab only the first `n` items * `takeWhile(coll?, f, ctx?)` &mdash; grab only the first items where the result of calling `f` with the item is truthy * `drop(coll?, n)` &mdash; drop the first `n` items and only include the rest * `dropWhile(coll?, f, ctx?)` &mdash; drop the first items where the result of calling `f` with the item is truthy * `dedupe(coll?)` &mdash; remove consecutive duplicates (equality compared with ===) The above functions optionally take a collection to immediately perform the transformation on, and a context to bind `this` to when calling `f`. That means you can call them in four ways: * Immediately perform a map: `map([1, 2, 3], x => x + 1)` * Same as above but call the function with `this` as `ctx`: `map([1, 2, 3], function(x) { return x + 1; }, ctx)` * Make a map transducer: `map(x => x + 1)` * Same as above but with `this` as `ctx`: `map(function(x) { return x + 1; }, ctx)` (I will be using the ES6 fat arrow syntax, but if that's not available just `function` instead) The signature of running an immediate map is the same familiar one as seen in lodash and underscore, but now you can drop the collection to make a transducer and run multiple transformations with good performance: ```js var transform = compose( map(x => x + 1), filter(x => x % 2 === 0), take(2) ); ``` `compose` is a provided function that simply turns `compose(f, g)` into `x => f(g(x))`. You use it to build up transformations. The above transformation would always run the map and filter **only twice** because only two items are needed, and it short-circuits once it gets two items. Again, this is done without laziness, read more [here](http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data). There are also 2 transducers available for taking collections and "catting" them into the transformation stream: * `cat` &mdash; take collections and forward each item individually, essentially flattening it * `mapcat(f)` &mdash; same as `cat`, but first apply `f` to each collection Just pass `cat` straight through like so: `compose(filter(x => x.length < 10), cat)`. That would take all arrays with a length less than 10 and flatten them out into a single array. ## Applying Transformations Building data structure-agnostic transformations is cool, but how do you actually use them? `transducers.js` provides several integration points. To use a transformation, we need to know how to iterate over the source data structure and how to build up a new one. The former is easy; we can work with arrays, objects, and anything can uses the ES6 iterator protocol (Maps, Sets, generators, etc). All the the below functions works with them. For the latter, you need to specify what you want back. The following functions allow you to make a new data structure and possibly apply a transformation: * `toArray(coll, xform?)` &mdash; Turn `coll` into an array, applying the transformation `xform` to each item if provided. The transform is optional in case you want to do something like turn an iterator into an array. * `toObj(coll, xform?)` &mdash; Turn `coll` into an object if possible, applying the transformation `xform` if provided. When an object is iterated it produces two-element arrays `[key, value]`, and `obj` will turn these back into an object. * `toIter(coll, xform?)` &mdash; Make an iterator over `coll`, and apply the transformation `xform` to each value if specified. Note that `coll` can just be another iterator. **Transformations will be applied lazily**. * `seq(coll, xform)` &mdash; A generalized method that will return the same data type that was passed in as `coll`, with `xform` applied. You will usually use this unless you know you want an array, object, or iterator. If `coll` is an iterator, another iterator will be returned and transformations will be applied lazily. * `into(to, xform, from)` &mdash; Apply `xform` to each item in `from` and append it to `to`. This has the effect of "pouring" elements into `to`. You will commonly use this when converting one type of object to another. * `transduce(coll, xform, reducer, init?)` &mdash; Like `reduce`, but apply `xform` to each value before passing to `reducer`. If `init` is not specify it will attempt to get it from `reducer`. The possibilities are endless: ```js // Map an object seq({ foo: 1, bar: 2 }, map(kv => [kv[0], kv[1] + 1])); // -> { foo: 2, bar: 3 } // Make an array from an object toArray({ foo: 1, bar: 2 }); // -> [ [ 'foo', 1 ], [ 'bar', 2 ] ] // Make an array from an iterable function* nums() { var i = 1; while(true) { yield i++; } } into([], take(3), nums()); // -> [ 1, 2, 3 ] // Lazily transform an iterable var iter = seq(nums(), compose(map(x => x * 2), filter(x => x > 4)); iter.next().value; // -> 6 iter.next().value; // -> 8 iter.next().value; // -> 10 ``` ## Laziness Transducers remove the requirement of being lazy to optimize for things like `take(10)`. However, it can still be useful to "bind" a collection to a set of transformations and pass it around, without actually evaluating the transformations. As noted above, whenever you apply transformations to an iterator it does so lazily. It's easy convert array transformations into a lazy operation, just use the utility function `iterator` to grab an iterator of the array instead: ```js seq(iterator([1, 2, 3]), compose( map(x => x + 1), filter(x => x % 2 === 0))) // -> <Iterator> ``` Our transformations are completely blind to the fact that our transformations may or may not be lazy. ## Utility Functions This library provides a few small utility functions: * `iterator(coll)` &mdash; Get an iterator for `coll`, which can be any type like array, object, iterator, or custom data type * `push(arr, value)` &mdash; Push `value` onto `arr` and return `arr` * `merge(obj, value)` &mdash; Merge `value` into `obj`. `value` can be another object or a two-element array of `[key, value]` * `range(n)` &mdash; Make an array of size `n` filled with numbers from `0..n`. ## immutable-js We've talked about how this can be applied to any data structure &mdash; let's see that in action. Here's how you could use this with [immutable-js](https://github.com/facebook/immutable-js). ```js Immutable.Vector.from( seq(Immutable.Vector(1, 2, 3, 4, 5), compose( map(function(x) { return x + 10; }), map(function(x) { return x * 2; }), filter(function(x) { return x % 5 === 0; }), filter(function(x) { return x % 2 === 0; }))) ) ``` We can use our familiar `seq` function because `Immutable.Vector` implements the iterator protocol, so we can iterator over it. Because `seq` is working with an iterator, it returns a new iterator that will *lazily transform each value*. We can simply pass this iterator into `Immutable.Vector.from` to construct a new one, and we have a new transformed immutable vector with no intermediate collections except for one lazy transformer! The builtin transformations perform well because they minimize allocations, but since we don't have any intermediate structures or laziness machinery, this performs slightly better. The point is not to beat it, but to show that both are high-performance but we can apply our performance to any data structure. ## CSP Channels This not only works with all the JavaScript data structures you can think of, but it even works for things like streams. Soon channels from [js-csp](https://github.com/ubolonton/js-csp) will be able to take a transformation and you get all of this for channels for free: ```js var ch = chan(1, compose( cat, map(x => x + 1), dedupe(), drop(3) )); ``` ## The `transducer` protocol While it's great that you can apply transducers to custom data structures, it's a bit annoying to always have to use constructor functions like `Immutable.Vector.from`. One option is to define a new protocol complementary to `iterator`. This conforms to the [official transducer spec](https://github.com/cognitect-labs/transducers-js/issues/20) so if you implement this, you can use it with all transducer libraries that conform to it. To implement the transducer protocol, you add methods to the prototype of your data structure. A transformer is an object with three methods: `init`, `result`, and `step`. `init` returns a new empty object, `result`, can perform any finalization steps on the resulting collection, and `step` performs a reduce. These methods are namespaced and in the future could be symbols. Here's what it looks like for `Immutable.Vector`: ```js t.filter(function(x) { return x % 5 === 0; }), t.filter(function(x) { return x % 2 === 0; }))); // -> List [ 30 ] ``` ## Running Tests ``` npm install gulp mocha build/tests ``` [BSD LICENSE](https://github.com/jlongster/transducers.js/blob/master/LICENSE) <MSG> use Immutable.List in examples <DFF> @@ -35,7 +35,7 @@ function* nums() { into([], transform, nums()); // -> [ 6, 12 ] -into([], transform, Immutable.Vector(1, 2, 3, 4, 5)) +into([], transform, Immutable.List.of(1, 2, 3, 4, 5)) // -> [ 6, 12 ] ``` @@ -157,7 +157,7 @@ This library provides a few small utility functions: We've talked about how this can be applied to any data structure &mdash; let's see that in action. Here's how you could use this with [immutable-js](https://github.com/facebook/immutable-js). ```js -Immutable.Vector.from( +Immutable.fromJS( seq(Immutable.Vector(1, 2, 3, 4, 5), compose( map(function(x) { return x + 10; }), @@ -186,32 +186,32 @@ var ch = chan(1, compose( ## The `transducer` protocol -While it's great that you can apply transducers to custom data structures, it's a bit annoying to always have to use constructor functions like `Immutable.Vector.from`. One option is to define a new protocol complementary to `iterator`. +While it's great that you can apply transducers to custom data structures, it's a bit annoying to always have to use constructor functions like `Immutable.fromJS`. One option is to define a new protocol complementary to `iterator`. This conforms to the [official transducer spec](https://github.com/cognitect-labs/transducers-js/issues/20) so if you implement this, you can use it with all transducer libraries that conform to it. To implement the transducer protocol, you add methods to the prototype of your data structure. A transformer is an object with three methods: `init`, `result`, and `step`. `init` returns a new empty object, `result`, can perform any finalization steps on the resulting collection, and `step` performs a reduce. -These methods are namespaced and in the future could be symbols. Here's what it looks like for `Immutable.Vector`: +These methods are namespaced and in the future could be symbols. Here's what it looks like for `Immutable.List`: ```js -Immutable.Vector.prototype['@@transducer/init'] = function() { - return Immutable.Vector().asMutable(); +Immutable.List.prototype['@@transducer/init'] = function() { + return Immutable.List().asMutable(); }; -Immutable.Vector.prototype['@@transducer/result'] = function(vec) { - return vec.asImmutable(); +Immutable.List.prototype['@@transducer/result'] = function(lst) { + return lst.asImmutable(); }; -Immutable.Vector.prototype['@@transducer/step'] = function(vec, x) { - return vec.push(x); +Immutable.List.prototype['@@transducer/step'] = function(lst, x) { + return lst.push(x); }; ``` If you implement the transducer protocol, now your data structure will work with *all* of the builtin functions. You can just use `seq` like normal and you get back an immutable vector! ```js -t.seq(Immutable.Vector(1, 2, 3, 4, 5), +t.seq(Immutable.List.of(1, 2, 3, 4, 5), t.compose( t.map(function(x) { return x + 10; }), t.map(function(x) { return x * 2; }),
11
use Immutable.List in examples
11
.md
md
bsd-2-clause
jlongster/transducers.js
10071998
<NME> jquery.meow.js <BEF> // jQuery Meow by Zachary Stewart (zacstewart.com) // // Copyright (c) 2011 Zachary Stewart // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (function ($, window) { 'use strict'; // Meow queue var default_meow_area, meows = { queue: {}, add: function (meow) { this.queue[meow.timestamp] = meow; }, get: function (timestamp) { return this.queue[timestamp]; }, remove: function (timestamp) { delete this.queue[timestamp]; }, size: function () { var timestamp, size = 0; for (timestamp in this.queue) { if (this.queue.hasOwnProperty(timestamp)) { size += 1; } } return size; } }, // Meow constructor Meow = function (options) { var that = this; this.timestamp = new Date().getTime(); // used to identify this meow and timeout this.hovered = false; // whether mouse is over or not if (typeof default_meow_area === 'undefined' && typeof options.container === 'undefined') { default_meow_area = $(window.document.createElement('div')) .attr({'id': ((new Date()).getTime()), 'class': 'meows'}); $('body').prepend(default_meow_area); } if (meows.size() <= 0) { if (typeof options.beforeCreateFirst === 'function') { options.beforeCreateFirst.call(that); } } if (typeof options.container === 'string') { this.container = $(options.container); } else { this.container = default_meow_area; } if (typeof options.title === 'string') { this.title = options.title; } if (typeof options.message === 'string') { this.message = options.message; } else if (options.message instanceof $) { if (options.message.is('input,textarea,select')) { this.message = options.message.val(); } else { this.message = options.message.text(); } if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') { this.title = options.message.attr('title'); } } if (typeof options.icon === 'string') { this.icon = options.icon; } if (options.sticky) { this.duration = Infinity; } else { this.duration = options.duration || 5000; } // Call callback if it's defined (this = meow object) if (typeof options.beforeCreate === 'function') { options.beforeCreate.call(that); } // Add the meow to the meow area this.container.append($(window.document.createElement('div')) .attr('id', 'meow-' + this.timestamp.toString()) .addClass('meow') .html($(window.document.createElement('div')).addClass('inner').html(this.message)) .hide() .fadeIn(400)); this.manifest = $('#meow-' + this.timestamp.toString()); // Add title if it's defined if (typeof this.title === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('h1')).text(this.title) ); } // Add icon if it's defined if (typeof that.icon === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('div')).addClass('icon').html( $(window.document.createElement('img')).attr('src', this.icon) ) ); } // Add close button if the meow isn't uncloseable // TODO: this close button needs to be much prettier if (options.closeable !== false) { this.manifest.find('.inner').prepend( $(window.document.createElement('a')) .addClass('close') .html('&times;') .attr('href', '#close-meow-' + that.timestamp) .click(function (e) { e.preventDefault(); that.destroy(); }) ); } this.manifest.bind('mouseenter mouseleave', function (event) { if (event.type === 'mouseleave') { that.hovered = false; that.manifest.removeClass('hover'); // Destroy the mow on mouseleave if it's timed out if (that.timestamp + that.duration <= new Date().getTime()) { that.destroy(); } } else { that.hovered = true; that.manifest.addClass('hover'); } }); // Add a timeout if the duration isn't Infinity if (this.duration !== Infinity) { this.timeout = window.setTimeout(function () { // Make sure this meow hasn't already been destroyed if (typeof meows.get(that.timestamp) !== 'undefined') { // Call callback if it's defined (this = meow DOM element) if (typeof options.onTimeout === 'function') { options.onTimeout.call(that.manifest); } // Don't destroy if user is hovering over meow if (that.hovered !== true && typeof that === 'object') { that.destroy(); } } }, that.duration); } this.destroy = function () { if (that.destroyed !== true) { // Call callback if it's defined (this = meow DOM element) if (typeof options.beforeDestroy === 'function') { options.beforeDestroy.call(that.manifest); } that.manifest.find('.inner').fadeTo(400, 0, function () { that.manifest.slideUp(function () { that.manifest.remove(); that.destroyed = true; meows.remove(that.timestamp); if (typeof options.afterDestroy === 'function') { options.afterDestroy.call(null); } if (meows.size() <= 0) { if (default_meow_area instanceof $) { default_meow_area.remove(); default_meow_area = undefined; } if (typeof options.afterDestroyLast === 'function') { options.afterDestroyLast.call(null); } } }); }); } }; }; $.fn.meow = function (args) { var meow = new Meow(args); meows.add(meow); return meow; }; $.meow = $.fn.meow; }(jQuery, window)); <MSG> Move license to its own file <DFF> @@ -1,26 +1,3 @@ -// jQuery Meow by Zachary Stewart (zacstewart.com) -// -// Copyright (c) 2011 Zachary Stewart -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - (function ($, window) { 'use strict'; // Meow queue
0
Move license to its own file
23
.js
meow
mit
zacstewart/Meow
10071999
<NME> jquery.meow.js <BEF> // jQuery Meow by Zachary Stewart (zacstewart.com) // // Copyright (c) 2011 Zachary Stewart // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (function ($, window) { 'use strict'; // Meow queue var default_meow_area, meows = { queue: {}, add: function (meow) { this.queue[meow.timestamp] = meow; }, get: function (timestamp) { return this.queue[timestamp]; }, remove: function (timestamp) { delete this.queue[timestamp]; }, size: function () { var timestamp, size = 0; for (timestamp in this.queue) { if (this.queue.hasOwnProperty(timestamp)) { size += 1; } } return size; } }, // Meow constructor Meow = function (options) { var that = this; this.timestamp = new Date().getTime(); // used to identify this meow and timeout this.hovered = false; // whether mouse is over or not if (typeof default_meow_area === 'undefined' && typeof options.container === 'undefined') { default_meow_area = $(window.document.createElement('div')) .attr({'id': ((new Date()).getTime()), 'class': 'meows'}); $('body').prepend(default_meow_area); } if (meows.size() <= 0) { if (typeof options.beforeCreateFirst === 'function') { options.beforeCreateFirst.call(that); } } if (typeof options.container === 'string') { this.container = $(options.container); } else { this.container = default_meow_area; } if (typeof options.title === 'string') { this.title = options.title; } if (typeof options.message === 'string') { this.message = options.message; } else if (options.message instanceof $) { if (options.message.is('input,textarea,select')) { this.message = options.message.val(); } else { this.message = options.message.text(); } if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') { this.title = options.message.attr('title'); } } if (typeof options.icon === 'string') { this.icon = options.icon; } if (options.sticky) { this.duration = Infinity; } else { this.duration = options.duration || 5000; } // Call callback if it's defined (this = meow object) if (typeof options.beforeCreate === 'function') { options.beforeCreate.call(that); } // Add the meow to the meow area this.container.append($(window.document.createElement('div')) .attr('id', 'meow-' + this.timestamp.toString()) .addClass('meow') .html($(window.document.createElement('div')).addClass('inner').html(this.message)) .hide() .fadeIn(400)); this.manifest = $('#meow-' + this.timestamp.toString()); // Add title if it's defined if (typeof this.title === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('h1')).text(this.title) ); } // Add icon if it's defined if (typeof that.icon === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('div')).addClass('icon').html( $(window.document.createElement('img')).attr('src', this.icon) ) ); } // Add close button if the meow isn't uncloseable // TODO: this close button needs to be much prettier if (options.closeable !== false) { this.manifest.find('.inner').prepend( $(window.document.createElement('a')) .addClass('close') .html('&times;') .attr('href', '#close-meow-' + that.timestamp) .click(function (e) { e.preventDefault(); that.destroy(); }) ); } this.manifest.bind('mouseenter mouseleave', function (event) { if (event.type === 'mouseleave') { that.hovered = false; that.manifest.removeClass('hover'); // Destroy the mow on mouseleave if it's timed out if (that.timestamp + that.duration <= new Date().getTime()) { that.destroy(); } } else { that.hovered = true; that.manifest.addClass('hover'); } }); // Add a timeout if the duration isn't Infinity if (this.duration !== Infinity) { this.timeout = window.setTimeout(function () { // Make sure this meow hasn't already been destroyed if (typeof meows.get(that.timestamp) !== 'undefined') { // Call callback if it's defined (this = meow DOM element) if (typeof options.onTimeout === 'function') { options.onTimeout.call(that.manifest); } // Don't destroy if user is hovering over meow if (that.hovered !== true && typeof that === 'object') { that.destroy(); } } }, that.duration); } this.destroy = function () { if (that.destroyed !== true) { // Call callback if it's defined (this = meow DOM element) if (typeof options.beforeDestroy === 'function') { options.beforeDestroy.call(that.manifest); } that.manifest.find('.inner').fadeTo(400, 0, function () { that.manifest.slideUp(function () { that.manifest.remove(); that.destroyed = true; meows.remove(that.timestamp); if (typeof options.afterDestroy === 'function') { options.afterDestroy.call(null); } if (meows.size() <= 0) { if (default_meow_area instanceof $) { default_meow_area.remove(); default_meow_area = undefined; } if (typeof options.afterDestroyLast === 'function') { options.afterDestroyLast.call(null); } } }); }); } }; }; $.fn.meow = function (args) { var meow = new Meow(args); meows.add(meow); return meow; }; $.meow = $.fn.meow; }(jQuery, window)); <MSG> Move license to its own file <DFF> @@ -1,26 +1,3 @@ -// jQuery Meow by Zachary Stewart (zacstewart.com) -// -// Copyright (c) 2011 Zachary Stewart -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - (function ($, window) { 'use strict'; // Meow queue
0
Move license to its own file
23
.js
meow
mit
zacstewart/Meow
10072000
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import parse from '../src/markup'; import createConfig from '../src/config'; import { OutputProfileOptions } from '../src/OutputProfile'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}>b'), '<div>\n\t<!-- <b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*2'), '<div>\n\t<!-- <b></b><b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*3'), '<div>\n\t<!-- \n\t<b></b>\n\t<b></b>\n\t<b></b>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); it('self-closing', () => { const xmlStyle = createProfile({ 'output.selfClosingStyle': 'xml' }); const htmlStyle = createProfile({ 'output.selfClosingStyle': 'html' }); const xhtmlStyle = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); }); it('boolean attributes', () => { const compact = createProfile({ 'output.compactBoolean': true }); const noCompact = createProfile({ 'output.compactBoolean': false }); equal(format('p[b.]', noCompact), '<p b="b"></p>'); equal(format('p[b.]', compact), '<p b></p>'); equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); }); it('no formatting', () => { const profile = createProfile({ 'output.format': false }); equal(format('div>p', profile), '<div><p></p></div>'); equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); }); it('format specific nodes', () => { equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); // https://github.com/emmetio/emmet/issues/446 equal(format('li>a'), '%li\n\t%a(href="") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); }); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Working implementation of Pug formatter <DFF> @@ -1,6 +1,7 @@ import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; +import pug from '../src/markup/format/pug'; import parse from '../src/markup'; import createConfig from '../src/config'; import { OutputProfileOptions } from '../src/OutputProfile'; @@ -177,4 +178,35 @@ describe('Format', () => { equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); + + describe('Pug', () => { + const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); + + it('basic', () => { + equal(format('div#header>ul.nav>li[title=test].nav-item*2'), + '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); + + equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), + '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); + + equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")/'); + }); + + it('nodes with text', () => { + equal(format('{Text 1}'), 'Text 1'); + equal(format('span{Text 1}'), 'span Text 1'); + equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); + equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); + equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); + }); + + it('generate fields', () => { + equal(format('a[href]', field), 'a(href="${1}") ${2}'); + equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); + equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); + equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); + equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); + equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")/'); + }); + }); });
32
Working implementation of Pug formatter
0
.ts
ts
mit
emmetio/emmet
10072001
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import parse from '../src/markup'; import createConfig from '../src/config'; import { OutputProfileOptions } from '../src/OutputProfile'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}>b'), '<div>\n\t<!-- <b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*2'), '<div>\n\t<!-- <b></b><b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*3'), '<div>\n\t<!-- \n\t<b></b>\n\t<b></b>\n\t<b></b>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); it('self-closing', () => { const xmlStyle = createProfile({ 'output.selfClosingStyle': 'xml' }); const htmlStyle = createProfile({ 'output.selfClosingStyle': 'html' }); const xhtmlStyle = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); }); it('boolean attributes', () => { const compact = createProfile({ 'output.compactBoolean': true }); const noCompact = createProfile({ 'output.compactBoolean': false }); equal(format('p[b.]', noCompact), '<p b="b"></p>'); equal(format('p[b.]', compact), '<p b></p>'); equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); }); it('no formatting', () => { const profile = createProfile({ 'output.format': false }); equal(format('div>p', profile), '<div><p></p></div>'); equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); }); it('format specific nodes', () => { equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); // https://github.com/emmetio/emmet/issues/446 equal(format('li>a'), '%li\n\t%a(href="") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); }); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Working implementation of Pug formatter <DFF> @@ -1,6 +1,7 @@ import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; +import pug from '../src/markup/format/pug'; import parse from '../src/markup'; import createConfig from '../src/config'; import { OutputProfileOptions } from '../src/OutputProfile'; @@ -177,4 +178,35 @@ describe('Format', () => { equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); + + describe('Pug', () => { + const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); + + it('basic', () => { + equal(format('div#header>ul.nav>li[title=test].nav-item*2'), + '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); + + equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), + '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); + + equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")/'); + }); + + it('nodes with text', () => { + equal(format('{Text 1}'), 'Text 1'); + equal(format('span{Text 1}'), 'span Text 1'); + equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); + equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); + equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); + }); + + it('generate fields', () => { + equal(format('a[href]', field), 'a(href="${1}") ${2}'); + equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); + equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); + equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); + equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); + equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")/'); + }); + }); });
32
Working implementation of Pug formatter
0
.ts
ts
mit
emmetio/emmet
10072002
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == "control" experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count { |k, v| k == experiment_key_without_version || v == "control" } experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/IndentationWidth <DFF> @@ -65,16 +65,16 @@ module Split end private - def keys_without_experiment(keys, experiment_key) - keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } - end + def keys_without_experiment(keys, experiment_key) + keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } + end - def keys_without_finished(keys) - keys.reject { |k| k.include?(":finished") } - end + def keys_without_finished(keys) + keys.reject { |k| k.include?(":finished") } + end - def key_without_version(key) - key.split(/\:\d(?!\:)/)[0] - end + def key_without_version(key) + key.split(/\:\d(?!\:)/)[0] + end end end
9
Fix Layout/IndentationWidth
9
.rb
rb
mit
splitrb/split
10072003
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == "control" experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count { |k, v| k == experiment_key_without_version || v == "control" } experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/IndentationWidth <DFF> @@ -65,16 +65,16 @@ module Split end private - def keys_without_experiment(keys, experiment_key) - keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } - end + def keys_without_experiment(keys, experiment_key) + keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } + end - def keys_without_finished(keys) - keys.reject { |k| k.include?(":finished") } - end + def keys_without_finished(keys) + keys.reject { |k| k.include?(":finished") } + end - def key_without_version(key) - key.split(/\:\d(?!\:)/)[0] - end + def key_without_version(key) + key.split(/\:\d(?!\:)/)[0] + end end end
9
Fix Layout/IndentationWidth
9
.rb
rb
mit
splitrb/split
10072004
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == "control" experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count { |k, v| k == experiment_key_without_version || v == "control" } experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/IndentationWidth <DFF> @@ -65,16 +65,16 @@ module Split end private - def keys_without_experiment(keys, experiment_key) - keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } - end + def keys_without_experiment(keys, experiment_key) + keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } + end - def keys_without_finished(keys) - keys.reject { |k| k.include?(":finished") } - end + def keys_without_finished(keys) + keys.reject { |k| k.include?(":finished") } + end - def key_without_version(key) - key.split(/\:\d(?!\:)/)[0] - end + def key_without_version(key) + key.split(/\:\d(?!\:)/)[0] + end end end
9
Fix Layout/IndentationWidth
9
.rb
rb
mit
splitrb/split
10072005
<NME> configuration_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Configuration do before(:each) { @config = Split::Configuration.new } it "should provide a default value for ignore_ip_addresses" do expect(@config.ignore_ip_addresses).to eq([]) end it "should provide default values for db failover" do expect(@config.db_failover).to be_falsey expect(@config.db_failover_on_db_error).to be_a Proc end it "should not allow multiple experiments by default" do expect(@config.allow_multiple_experiments).to be_falsey end it "should be enabled by default" do expect(@config.enabled).to be_truthy end it "disabled is the opposite of enabled" do @config.enabled = false expect(@config.disabled?).to be_truthy end it "should not store the overridden test group per default" do expect(@config.store_override).to be_falsey end it "should provide a default pattern for robots" do %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg YandexBot AdsBot-Google Wget curl bitlybot facebookexternalhit spider].each do |robot| expect(@config.robot_regex).to match(robot) end expect(@config.robot_regex).to match("EventMachine HttpClient") expect(@config.robot_regex).to match("libwww-perl/5.836") expect(@config.robot_regex).to match("Pingdom.com_bot_version_1.4_(http://www.pingdom.com)") expect(@config.robot_regex).to match(" - ") end it "should accept real UAs with the robot regexp" do expect(@config.robot_regex).not_to match("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0") expect(@config.robot_regex).not_to match("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; F-6.0SP2-20041109; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322; InfoPath.3)") end it "should allow adding a bot to the bot list" do @config.bots["newbot"] = "An amazing test bot" expect(@config.robot_regex).to match("newbot") @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end it "should normalize experiments" do @config.experiments = { :my_experiment => { eos @config.experiments = YAML.load(experiments_yaml) end ], } } @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end expect(@config.metrics.keys).to eq([:my_metric]) end end end context "as symbols" do context "with valid YAML" do before do experiments_yaml = <<-eos :my_experiment: :alternatives: - Control Opt - Alt One - Alt Two :resettable: false eos @config.experiments = YAML.load(experiments_yaml) end it "should normalize experiments" do expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } }) end end context "with invalid YAML" do let(:yaml) { YAML.load(input) } context "with an empty string" do let(:input) { "" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end context "with just the YAML header" do let(:input) { "---" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end end end end it "should normalize experiments" do @config.experiments = { my_experiment: { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } } expect(@config.normalized_experiments).to eq({ my_experiment: { alternatives: [{ "control_opt"=>0.67 }, [{ "second_opt"=>0.1 }, { "third_opt"=>0.23 }]] } }) end context "redis configuration" do it "should default to local redis server" do old_redis_url = ENV["REDIS_URL"] ENV.delete("REDIS_URL") expect(Split::Configuration.new.redis).to eq("redis://localhost:6379") ENV["REDIS_URL"] = old_redis_url end it "should allow for redis url to be configured" do @config.redis = "custom_redis_url" expect(@config.redis).to eq("custom_redis_url") end context "provided REDIS_URL environment variable" do it "should use the ENV variable" do old_redis_url = ENV["REDIS_URL"] ENV["REDIS_URL"] = "env_redis_url" expect(Split::Configuration.new.redis).to eq("env_redis_url") ENV["REDIS_URL"] = old_redis_url end end end context "persistence cookie length" do it "should default to 1 year" do expect(@config.persistence_cookie_length).to eq(31536000) end it "should allow the persistence cookie length to be configured" do @config.persistence_cookie_length = 2592000 expect(@config.persistence_cookie_length).to eq(2592000) end end context "persistence cookie domain" do it "should default to nil" do expect(@config.persistence_cookie_domain).to eq(nil) end it "should allow the persistence cookie domain to be configured" do @config.persistence_cookie_domain = ".acme.com" expect(@config.persistence_cookie_domain).to eq(".acme.com") end end end <MSG> Load experiments via YAML indifferently. Fixes #123. <DFF> @@ -54,13 +54,85 @@ describe Split::Configuration do @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end - + it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end - + + context "when experiments are defined via YAML" do + context "as strings" do + context "in a basic configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - Control Opt + - Alt One + - Alt Two + resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it 'should normalize experiments' do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + + context "in a complex configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - name: Control Opt + percent: 67 + - name: Alt One + percent: 10 + - name: Alt Two + percent: 23 + resettable: false + metric: my_metric + another_experiment: + alternatives: + - a + - b + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"Control Opt"=>0.67}, + [{"Alt One"=>0.1}, {"Alt Two"=>0.23}]]}, :another_experiment=>{:alternatives=>["a", ["b"]]}} + end + + it "should recognize metrics" do + @config.metrics.should_not be_nil + @config.metrics.keys.should == [:my_metric] + end + end + end + + context "as symbols" do + before do + experiments_yaml = <<-eos + :my_experiment: + :alternatives: + - Control Opt + - Alt One + - Alt Two + :resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + end + it "should normalize experiments" do @config.experiments = { :my_experiment => { @@ -71,7 +143,7 @@ describe Split::Configuration do ], } } - + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end
75
Load experiments via YAML indifferently.
3
.rb
rb
mit
splitrb/split
10072006
<NME> configuration_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Configuration do before(:each) { @config = Split::Configuration.new } it "should provide a default value for ignore_ip_addresses" do expect(@config.ignore_ip_addresses).to eq([]) end it "should provide default values for db failover" do expect(@config.db_failover).to be_falsey expect(@config.db_failover_on_db_error).to be_a Proc end it "should not allow multiple experiments by default" do expect(@config.allow_multiple_experiments).to be_falsey end it "should be enabled by default" do expect(@config.enabled).to be_truthy end it "disabled is the opposite of enabled" do @config.enabled = false expect(@config.disabled?).to be_truthy end it "should not store the overridden test group per default" do expect(@config.store_override).to be_falsey end it "should provide a default pattern for robots" do %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg YandexBot AdsBot-Google Wget curl bitlybot facebookexternalhit spider].each do |robot| expect(@config.robot_regex).to match(robot) end expect(@config.robot_regex).to match("EventMachine HttpClient") expect(@config.robot_regex).to match("libwww-perl/5.836") expect(@config.robot_regex).to match("Pingdom.com_bot_version_1.4_(http://www.pingdom.com)") expect(@config.robot_regex).to match(" - ") end it "should accept real UAs with the robot regexp" do expect(@config.robot_regex).not_to match("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0") expect(@config.robot_regex).not_to match("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; F-6.0SP2-20041109; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322; InfoPath.3)") end it "should allow adding a bot to the bot list" do @config.bots["newbot"] = "An amazing test bot" expect(@config.robot_regex).to match("newbot") @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end it "should normalize experiments" do @config.experiments = { :my_experiment => { eos @config.experiments = YAML.load(experiments_yaml) end ], } } @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end expect(@config.metrics.keys).to eq([:my_metric]) end end end context "as symbols" do context "with valid YAML" do before do experiments_yaml = <<-eos :my_experiment: :alternatives: - Control Opt - Alt One - Alt Two :resettable: false eos @config.experiments = YAML.load(experiments_yaml) end it "should normalize experiments" do expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } }) end end context "with invalid YAML" do let(:yaml) { YAML.load(input) } context "with an empty string" do let(:input) { "" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end context "with just the YAML header" do let(:input) { "---" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end end end end it "should normalize experiments" do @config.experiments = { my_experiment: { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } } expect(@config.normalized_experiments).to eq({ my_experiment: { alternatives: [{ "control_opt"=>0.67 }, [{ "second_opt"=>0.1 }, { "third_opt"=>0.23 }]] } }) end context "redis configuration" do it "should default to local redis server" do old_redis_url = ENV["REDIS_URL"] ENV.delete("REDIS_URL") expect(Split::Configuration.new.redis).to eq("redis://localhost:6379") ENV["REDIS_URL"] = old_redis_url end it "should allow for redis url to be configured" do @config.redis = "custom_redis_url" expect(@config.redis).to eq("custom_redis_url") end context "provided REDIS_URL environment variable" do it "should use the ENV variable" do old_redis_url = ENV["REDIS_URL"] ENV["REDIS_URL"] = "env_redis_url" expect(Split::Configuration.new.redis).to eq("env_redis_url") ENV["REDIS_URL"] = old_redis_url end end end context "persistence cookie length" do it "should default to 1 year" do expect(@config.persistence_cookie_length).to eq(31536000) end it "should allow the persistence cookie length to be configured" do @config.persistence_cookie_length = 2592000 expect(@config.persistence_cookie_length).to eq(2592000) end end context "persistence cookie domain" do it "should default to nil" do expect(@config.persistence_cookie_domain).to eq(nil) end it "should allow the persistence cookie domain to be configured" do @config.persistence_cookie_domain = ".acme.com" expect(@config.persistence_cookie_domain).to eq(".acme.com") end end end <MSG> Load experiments via YAML indifferently. Fixes #123. <DFF> @@ -54,13 +54,85 @@ describe Split::Configuration do @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end - + it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end - + + context "when experiments are defined via YAML" do + context "as strings" do + context "in a basic configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - Control Opt + - Alt One + - Alt Two + resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it 'should normalize experiments' do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + + context "in a complex configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - name: Control Opt + percent: 67 + - name: Alt One + percent: 10 + - name: Alt Two + percent: 23 + resettable: false + metric: my_metric + another_experiment: + alternatives: + - a + - b + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"Control Opt"=>0.67}, + [{"Alt One"=>0.1}, {"Alt Two"=>0.23}]]}, :another_experiment=>{:alternatives=>["a", ["b"]]}} + end + + it "should recognize metrics" do + @config.metrics.should_not be_nil + @config.metrics.keys.should == [:my_metric] + end + end + end + + context "as symbols" do + before do + experiments_yaml = <<-eos + :my_experiment: + :alternatives: + - Control Opt + - Alt One + - Alt Two + :resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + end + it "should normalize experiments" do @config.experiments = { :my_experiment => { @@ -71,7 +143,7 @@ describe Split::Configuration do ], } } - + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end
75
Load experiments via YAML indifferently.
3
.rb
rb
mit
splitrb/split
10072007
<NME> configuration_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Configuration do before(:each) { @config = Split::Configuration.new } it "should provide a default value for ignore_ip_addresses" do expect(@config.ignore_ip_addresses).to eq([]) end it "should provide default values for db failover" do expect(@config.db_failover).to be_falsey expect(@config.db_failover_on_db_error).to be_a Proc end it "should not allow multiple experiments by default" do expect(@config.allow_multiple_experiments).to be_falsey end it "should be enabled by default" do expect(@config.enabled).to be_truthy end it "disabled is the opposite of enabled" do @config.enabled = false expect(@config.disabled?).to be_truthy end it "should not store the overridden test group per default" do expect(@config.store_override).to be_falsey end it "should provide a default pattern for robots" do %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg YandexBot AdsBot-Google Wget curl bitlybot facebookexternalhit spider].each do |robot| expect(@config.robot_regex).to match(robot) end expect(@config.robot_regex).to match("EventMachine HttpClient") expect(@config.robot_regex).to match("libwww-perl/5.836") expect(@config.robot_regex).to match("Pingdom.com_bot_version_1.4_(http://www.pingdom.com)") expect(@config.robot_regex).to match(" - ") end it "should accept real UAs with the robot regexp" do expect(@config.robot_regex).not_to match("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0") expect(@config.robot_regex).not_to match("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; F-6.0SP2-20041109; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322; InfoPath.3)") end it "should allow adding a bot to the bot list" do @config.bots["newbot"] = "An amazing test bot" expect(@config.robot_regex).to match("newbot") @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end it "should normalize experiments" do @config.experiments = { :my_experiment => { eos @config.experiments = YAML.load(experiments_yaml) end ], } } @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end expect(@config.metrics.keys).to eq([:my_metric]) end end end context "as symbols" do context "with valid YAML" do before do experiments_yaml = <<-eos :my_experiment: :alternatives: - Control Opt - Alt One - Alt Two :resettable: false eos @config.experiments = YAML.load(experiments_yaml) end it "should normalize experiments" do expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } }) end end context "with invalid YAML" do let(:yaml) { YAML.load(input) } context "with an empty string" do let(:input) { "" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end context "with just the YAML header" do let(:input) { "---" } it "should raise an error" do expect { @config.experiments = yaml }.to raise_error(Split::InvalidExperimentsFormatError) end end end end end it "should normalize experiments" do @config.experiments = { my_experiment: { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } } expect(@config.normalized_experiments).to eq({ my_experiment: { alternatives: [{ "control_opt"=>0.67 }, [{ "second_opt"=>0.1 }, { "third_opt"=>0.23 }]] } }) end context "redis configuration" do it "should default to local redis server" do old_redis_url = ENV["REDIS_URL"] ENV.delete("REDIS_URL") expect(Split::Configuration.new.redis).to eq("redis://localhost:6379") ENV["REDIS_URL"] = old_redis_url end it "should allow for redis url to be configured" do @config.redis = "custom_redis_url" expect(@config.redis).to eq("custom_redis_url") end context "provided REDIS_URL environment variable" do it "should use the ENV variable" do old_redis_url = ENV["REDIS_URL"] ENV["REDIS_URL"] = "env_redis_url" expect(Split::Configuration.new.redis).to eq("env_redis_url") ENV["REDIS_URL"] = old_redis_url end end end context "persistence cookie length" do it "should default to 1 year" do expect(@config.persistence_cookie_length).to eq(31536000) end it "should allow the persistence cookie length to be configured" do @config.persistence_cookie_length = 2592000 expect(@config.persistence_cookie_length).to eq(2592000) end end context "persistence cookie domain" do it "should default to nil" do expect(@config.persistence_cookie_domain).to eq(nil) end it "should allow the persistence cookie domain to be configured" do @config.persistence_cookie_domain = ".acme.com" expect(@config.persistence_cookie_domain).to eq(".acme.com") end end end <MSG> Load experiments via YAML indifferently. Fixes #123. <DFF> @@ -54,13 +54,85 @@ describe Split::Configuration do @config.metrics.should_not be_nil @config.metrics.keys.should == [:my_metric] end - + it "should allow loading of experiment using experment_for" do @config.experiments = {:my_experiment=> {:alternatives=>["control_opt", "other_opt"], :metric=>:my_metric}} @config.experiment_for(:my_experiment).should == {:alternatives=>["control_opt", ["other_opt"]]} end - + + context "when experiments are defined via YAML" do + context "as strings" do + context "in a basic configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - Control Opt + - Alt One + - Alt Two + resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it 'should normalize experiments' do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + + context "in a complex configuration" do + before do + experiments_yaml = <<-eos + my_experiment: + alternatives: + - name: Control Opt + percent: 67 + - name: Alt One + percent: 10 + - name: Alt Two + percent: 23 + resettable: false + metric: my_metric + another_experiment: + alternatives: + - a + - b + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"Control Opt"=>0.67}, + [{"Alt One"=>0.1}, {"Alt Two"=>0.23}]]}, :another_experiment=>{:alternatives=>["a", ["b"]]}} + end + + it "should recognize metrics" do + @config.metrics.should_not be_nil + @config.metrics.keys.should == [:my_metric] + end + end + end + + context "as symbols" do + before do + experiments_yaml = <<-eos + :my_experiment: + :alternatives: + - Control Opt + - Alt One + - Alt Two + :resettable: false + eos + @config.experiments = YAML.load(experiments_yaml) + end + + it "should normalize experiments" do + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>["Control Opt", ["Alt One", "Alt Two"]]}} + end + end + end + it "should normalize experiments" do @config.experiments = { :my_experiment => { @@ -71,7 +143,7 @@ describe Split::Configuration do ], } } - + @config.normalized_experiments.should == {:my_experiment=>{:alternatives=>[{"control_opt"=>0.67}, [{"second_opt"=>0.1}, {"third_opt"=>0.23}]]}} end end
75
Load experiments via YAML indifferently.
3
.rb
rb
mit
splitrb/split
10072008
<NME> .travis.yml <BEF> ADDFILE <MSG> chore(.travis.yml): Added .travis.yml for Travis-CI integration <DFF> @@ -0,0 +1,11 @@ +language: node_js + +node_js: + - 0.10 + - 0.11 + +before_script: + - npm install -g gulp + +script: + - gulp test \ No newline at end of file
11
chore(.travis.yml): Added .travis.yml for Travis-CI integration
0
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072009
<NME> .travis.yml <BEF> ADDFILE <MSG> chore(.travis.yml): Added .travis.yml for Travis-CI integration <DFF> @@ -0,0 +1,11 @@ +language: node_js + +node_js: + - 0.10 + - 0.11 + +before_script: + - npm install -g gulp + +script: + - gulp test \ No newline at end of file
11
chore(.travis.yml): Added .travis.yml for Travis-CI integration
0
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072010
<NME> .travis.yml <BEF> ADDFILE <MSG> chore(.travis.yml): Added .travis.yml for Travis-CI integration <DFF> @@ -0,0 +1,11 @@ +language: node_js + +node_js: + - 0.10 + - 0.11 + +before_script: + - npm install -g gulp + +script: + - gulp test \ No newline at end of file
11
chore(.travis.yml): Added .travis.yml for Travis-CI integration
0
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072011
<NME> utils.py <BEF> ADDFILE <MSG> Merge branch 'master' of git://github.com/ask/chishop <DFF> @@ -0,0 +1,38 @@ +import sys +import traceback + +from django.core.files.uploadedfile import SimpleUploadedFile +from django.utils.datastructures import MultiValueDict + + +def transmute(f): + if hasattr(f, "filename") and f.filename: + v = SimpleUploadedFile(f.filename, f.value, f.type) + else: + v = f.value.decode("utf-8") + return v + + +def decode_fs(fs): + POST, FILES = {}, {} + for k in fs.keys(): + v = transmute(fs[k]) + if isinstance(v, SimpleUploadedFile): + FILES[k] = [v] + else: + # Distutils sends UNKNOWN for empty fields (e.g platform) + # [russell.sim@gmail.com] + if v == "UNKNOWN": + v = None + POST[k] = [v] + return MultiValueDict(POST), MultiValueDict(FILES) + + +def debug(func): + # @debug is handy when debugging distutils requests + def _wrapped(*args, **kwargs): + try: + return func(*args, **kwargs) + except: + traceback.print_exception(*sys.exc_info()) + return _wrapped \ No newline at end of file
38
Merge branch 'master' of git://github.com/ask/chishop
0
.py
py
bsd-3-clause
ask/chishop
10072012
<NME> ci.yml <BEF> name: split on: [push] jobs: test: strategy: matrix: include: - gemfile: 5.2.gemfile ruby: 2.5 - gemfile: 5.2.gemfile ruby: 2.6 - gemfile: 5.2.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: 2.5 - gemfile: 6.0.gemfile ruby: 2.6 - gemfile: 6.0.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: '3.0' - gemfile: 6.1.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.1' runs-on: ubuntu-latest services: redis: image: redis ports: ['6379:6379'] options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - name: Install dependencies run: | bundle config set gemfile "${GITHUB_WORKSPACE}/gemfiles/${{ matrix.gemfile }}" bundle install --jobs 4 --retry 3 - name: Display Ruby version run: ruby -v - name: Test run: bundle exec rspec env: REDIS_URL: redis:6379 - name: Rubocop run: bundle exec rubocop <MSG> Update actions/checkout to v3 <DFF> @@ -51,7 +51,7 @@ jobs: --health-retries 5 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: ruby/setup-ruby@v1 with:
1
Update actions/checkout to v3
1
.yml
github/workflows/ci
mit
splitrb/split
10072013
<NME> ci.yml <BEF> name: split on: [push] jobs: test: strategy: matrix: include: - gemfile: 5.2.gemfile ruby: 2.5 - gemfile: 5.2.gemfile ruby: 2.6 - gemfile: 5.2.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: 2.5 - gemfile: 6.0.gemfile ruby: 2.6 - gemfile: 6.0.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: '3.0' - gemfile: 6.1.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.1' runs-on: ubuntu-latest services: redis: image: redis ports: ['6379:6379'] options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - name: Install dependencies run: | bundle config set gemfile "${GITHUB_WORKSPACE}/gemfiles/${{ matrix.gemfile }}" bundle install --jobs 4 --retry 3 - name: Display Ruby version run: ruby -v - name: Test run: bundle exec rspec env: REDIS_URL: redis:6379 - name: Rubocop run: bundle exec rubocop <MSG> Update actions/checkout to v3 <DFF> @@ -51,7 +51,7 @@ jobs: --health-retries 5 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: ruby/setup-ruby@v1 with:
1
Update actions/checkout to v3
1
.yml
github/workflows/ci
mit
splitrb/split
10072014
<NME> ci.yml <BEF> name: split on: [push] jobs: test: strategy: matrix: include: - gemfile: 5.2.gemfile ruby: 2.5 - gemfile: 5.2.gemfile ruby: 2.6 - gemfile: 5.2.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: 2.5 - gemfile: 6.0.gemfile ruby: 2.6 - gemfile: 6.0.gemfile ruby: 2.7 - gemfile: 6.0.gemfile ruby: '3.0' - gemfile: 6.1.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.0' - gemfile: 7.0.gemfile ruby: '3.1' runs-on: ubuntu-latest services: redis: image: redis ports: ['6379:6379'] options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - name: Install dependencies run: | bundle config set gemfile "${GITHUB_WORKSPACE}/gemfiles/${{ matrix.gemfile }}" bundle install --jobs 4 --retry 3 - name: Display Ruby version run: ruby -v - name: Test run: bundle exec rspec env: REDIS_URL: redis:6379 - name: Rubocop run: bundle exec rubocop <MSG> Update actions/checkout to v3 <DFF> @@ -51,7 +51,7 @@ jobs: --health-retries 5 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: ruby/setup-ruby@v1 with:
1
Update actions/checkout to v3
1
.yml
github/workflows/ci
mit
splitrb/split
10072015
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Rescue from Redis::BaseError in #ab_test Redis defines a number of different exception classes (see https://github.com/redis/redis-rb/blob/1bd43346cdf71ba69176612714616289a5a70ed4/lib/redis/errors.rb for details). When Redis raises an exception, we need to be able to have the db_failover configuration used, whether it's a failure to connect, a timeout, or an invalid command. We ran into this issue when our Redis instance ran out of memory. In that case (and most others), Split should be able to handle things gracefully. <DFF> @@ -16,7 +16,7 @@ module Split else control_variable(experiment.control) end - rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e + rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e)
1
Rescue from Redis::BaseError in #ab_test
1
.rb
rb
mit
splitrb/split
10072016
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Rescue from Redis::BaseError in #ab_test Redis defines a number of different exception classes (see https://github.com/redis/redis-rb/blob/1bd43346cdf71ba69176612714616289a5a70ed4/lib/redis/errors.rb for details). When Redis raises an exception, we need to be able to have the db_failover configuration used, whether it's a failure to connect, a timeout, or an invalid command. We ran into this issue when our Redis instance ran out of memory. In that case (and most others), Split should be able to handle things gracefully. <DFF> @@ -16,7 +16,7 @@ module Split else control_variable(experiment.control) end - rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e + rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e)
1
Rescue from Redis::BaseError in #ab_test
1
.rb
rb
mit
splitrb/split
10072017
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| next if override_present?(experiment.key) finish_experiment(experiment, options.merge(goals: goals)) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_record_extra_info(metric_descriptor, key, value = 1) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, _ = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) if experiments.any? experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> Rescue from Redis::BaseError in #ab_test Redis defines a number of different exception classes (see https://github.com/redis/redis-rb/blob/1bd43346cdf71ba69176612714616289a5a70ed4/lib/redis/errors.rb for details). When Redis raises an exception, we need to be able to have the db_failover configuration used, whether it's a failure to connect, a timeout, or an invalid command. We ran into this issue when our Redis instance ran out of memory. In that case (and most others), Split should be able to handle things gracefully. <DFF> @@ -16,7 +16,7 @@ module Split else control_variable(experiment.control) end - rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e + rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e)
1
Rescue from Redis::BaseError in #ab_test
1
.rb
rb
mit
splitrb/split
10072018
<NME> convert.ts <BEF> ADDFILE <MSG> Convert abbreviation to tree <DFF> @@ -0,0 +1,17 @@ +import { equal } from 'assert'; +import parser, { ParserOptions } from '../src'; +import stringify from './assets/stringify-node'; + +function parse(abbr: string, options?: ParserOptions) { + return stringify(parser(abbr, options)); +} + +describe('Convert token abbreviations', () => { + it('basic', () => { + equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>'); + equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>'); + equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>'); + equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>'); + equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>'); + }); +});
17
Convert abbreviation to tree
0
.ts
ts
mit
emmetio/emmet
10072019
<NME> convert.ts <BEF> ADDFILE <MSG> Convert abbreviation to tree <DFF> @@ -0,0 +1,17 @@ +import { equal } from 'assert'; +import parser, { ParserOptions } from '../src'; +import stringify from './assets/stringify-node'; + +function parse(abbr: string, options?: ParserOptions) { + return stringify(parser(abbr, options)); +} + +describe('Convert token abbreviations', () => { + it('basic', () => { + equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>'); + equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>'); + equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>'); + equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>'); + equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>'); + }); +});
17
Convert abbreviation to tree
0
.ts
ts
mit
emmetio/emmet
10072020
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals def initialize(name, options = {}) options = { attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? start unless Split.configuration.start_manually persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually persist_experiment_configuration end redis.hmset(experiment_config_key, :resettable, resettable.to_s, :algorithm, algorithm.to_s) self end def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end alternatives.find{|a| a.name == name} end def alternatives @alternatives.dup end def next_alternative winner || random_alternative end self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Don't duplicate alternatives on access Not sure why this was put in place, but it seems dangerous. <DFF> @@ -4,6 +4,7 @@ module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals + attr_accessor :alternatives def initialize(name, options = {}) options = { @@ -99,10 +100,6 @@ module Split alternatives.find{|a| a.name == name} end - def alternatives - @alternatives.dup - end - def next_alternative winner || random_alternative end
1
Don't duplicate alternatives on access
4
.rb
rb
mit
splitrb/split
10072021
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals def initialize(name, options = {}) options = { attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? start unless Split.configuration.start_manually persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually persist_experiment_configuration end redis.hmset(experiment_config_key, :resettable, resettable.to_s, :algorithm, algorithm.to_s) self end def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end alternatives.find{|a| a.name == name} end def alternatives @alternatives.dup end def next_alternative winner || random_alternative end self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Don't duplicate alternatives on access Not sure why this was put in place, but it seems dangerous. <DFF> @@ -4,6 +4,7 @@ module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals + attr_accessor :alternatives def initialize(name, options = {}) options = { @@ -99,10 +100,6 @@ module Split alternatives.find{|a| a.name == name} end - def alternatives - @alternatives.dup - end - def next_alternative winner || random_alternative end
1
Don't duplicate alternatives on access
4
.rb
rb
mit
splitrb/split
10072022
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals def initialize(name, options = {}) options = { attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? start unless Split.configuration.start_manually persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually persist_experiment_configuration end redis.hmset(experiment_config_key, :resettable, resettable.to_s, :algorithm, algorithm.to_s) self end def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end alternatives.find{|a| a.name == name} end def alternatives @alternatives.dup end def next_alternative winner || random_alternative end self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Don't duplicate alternatives on access Not sure why this was put in place, but it seems dangerous. <DFF> @@ -4,6 +4,7 @@ module Split attr_writer :algorithm attr_accessor :resettable attr_accessor :goals + attr_accessor :alternatives def initialize(name, options = {}) options = { @@ -99,10 +100,6 @@ module Split alternatives.find{|a| a.name == name} end - def alternatives - @alternatives.dup - end - def next_alternative winner || random_alternative end
1
Don't duplicate alternatives on access
4
.rb
rb
mit
splitrb/split
10072023
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) Split.configuration.db_failover_on_db_error.call(e) end def finished(metric_descriptor, options = {:reset => true}) warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' ab_finished(metric_descriptor, options) end def override_present?(experiment_name) override_alternative(experiment_name) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end defined?(params) && params['SPLIT_DISABLE'] end def begin_experiment(experiment, alternative_name = nil) warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' alternative_name ||= experiment.control.name ab_user[experiment.key] = alternative_name alternative_name end def ab_user @ab_user ||= User.new(self) end experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> removed deprecated methods <DFF> @@ -76,11 +76,6 @@ module Split Split.configuration.db_failover_on_db_error.call(e) end - def finished(metric_descriptor, options = {:reset => true}) - warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' - ab_finished(metric_descriptor, options) - end - def override_present?(experiment_name) override_alternative(experiment_name) end @@ -93,13 +88,6 @@ module Split defined?(params) && params['SPLIT_DISABLE'] end - def begin_experiment(experiment, alternative_name = nil) - warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' - alternative_name ||= experiment.control.name - ab_user[experiment.key] = alternative_name - alternative_name - end - def ab_user @ab_user ||= User.new(self) end
0
removed deprecated methods
12
.rb
rb
mit
splitrb/split
10072024
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) Split.configuration.db_failover_on_db_error.call(e) end def finished(metric_descriptor, options = {:reset => true}) warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' ab_finished(metric_descriptor, options) end def override_present?(experiment_name) override_alternative(experiment_name) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end defined?(params) && params['SPLIT_DISABLE'] end def begin_experiment(experiment, alternative_name = nil) warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' alternative_name ||= experiment.control.name ab_user[experiment.key] = alternative_name alternative_name end def ab_user @ab_user ||= User.new(self) end experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> removed deprecated methods <DFF> @@ -76,11 +76,6 @@ module Split Split.configuration.db_failover_on_db_error.call(e) end - def finished(metric_descriptor, options = {:reset => true}) - warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' - ab_finished(metric_descriptor, options) - end - def override_present?(experiment_name) override_alternative(experiment_name) end @@ -93,13 +88,6 @@ module Split defined?(params) && params['SPLIT_DISABLE'] end - def begin_experiment(experiment, alternative_name = nil) - warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' - alternative_name ||= experiment.control.name - ab_user[experiment.key] = alternative_name - alternative_name - end - def ab_user @ab_user ||= User.new(self) end
0
removed deprecated methods
12
.rb
rb
mit
splitrb/split
10072025
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function def ab_test(metric_descriptor, control = nil, *alternatives) begin experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives) alternative = if Split.configuration.enabled && !exclude_visitor? experiment.save raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e raise(e) unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) if Split.configuration.db_failover_allow_parameter_override alternative = override_alternative(experiment.name) if override_present?(experiment.name) alternative = control_variable(experiment.control) if split_generically_disabled? end ensure alternative ||= control_variable(experiment.control) end if block_given? metadata = experiment.metadata[alternative] if experiment.metadata yield(alternative, metadata || {}) else alternative end end def reset!(experiment) ab_user.delete(experiment.key) end def finish_experiment(experiment, options = { reset: true }) return false if active_experiments[experiment.name].nil? return true if experiment.has_winner? should_reset = experiment.resettable? && options[:reset] if ab_user[experiment.finished_key] && !should_reset true else alternative_name = ab_user[experiment.key] trial = Trial.new( user: ab_user, experiment: experiment, alternative: alternative_name, goals: options[:goals], ) trial.complete!(self) if should_reset reset!(experiment) else ab_user[experiment.finished_key] = true end end end def ab_finished(metric_descriptor, options = { reset: true }) return if exclude_visitor? || Split.configuration.disabled? metric_descriptor, goals = normalize_metric(metric_descriptor) experiments = Metric.possible_experiments(metric_descriptor) Split.configuration.db_failover_on_db_error.call(e) end def finished(metric_descriptor, options = {:reset => true}) warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' ab_finished(metric_descriptor, options) end def override_present?(experiment_name) override_alternative(experiment_name) end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end defined?(params) && params['SPLIT_DISABLE'] end def begin_experiment(experiment, alternative_name = nil) warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' alternative_name ||= experiment.control.name ab_user[experiment.key] = alternative_name alternative_name end def ab_user @ab_user ||= User.new(self) end experiments.each do |experiment| alternative_name = ab_user[experiment.key] if alternative_name alternative = experiment.alternatives.find { |alt| alt.name == alternative_name } alternative.record_extra_info(key, value) if alternative end end end rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def ab_active_experiments ab_user.active_experiments rescue => e raise unless Split.configuration.db_failover Split.configuration.db_failover_on_db_error.call(e) end def override_present?(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative(experiment_name) override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name) end def override_alternative_by_params(experiment_name) defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name] end def override_alternative_by_cookies(experiment_name) return unless defined?(request) if request.cookies && request.cookies.key?("split_override") experiments = JSON.parse(request.cookies["split_override"]) rescue {} experiments[experiment_name] end end def split_generically_disabled? defined?(params) && params["SPLIT_DISABLE"] end def ab_user @ab_user ||= User.new(self) end def exclude_visitor? defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?) end def is_robot? defined?(request) && request.user_agent =~ Split.configuration.robot_regex end def is_preview? defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview" end def is_ignored_ip_address? return false if Split.configuration.ignore_ip_addresses.empty? Split.configuration.ignore_ip_addresses.each do |ip| return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip)) end false end def active_experiments ab_user.active_experiments end def normalize_metric(metric_descriptor) if Hash === metric_descriptor experiment_name = metric_descriptor.keys.first goals = Array(metric_descriptor.values.first) else experiment_name = metric_descriptor goals = [] end return experiment_name, goals end def control_variable(control) Hash === control ? control.keys.first.to_s : control.to_s end end end <MSG> removed deprecated methods <DFF> @@ -76,11 +76,6 @@ module Split Split.configuration.db_failover_on_db_error.call(e) end - def finished(metric_descriptor, options = {:reset => true}) - warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0' - ab_finished(metric_descriptor, options) - end - def override_present?(experiment_name) override_alternative(experiment_name) end @@ -93,13 +88,6 @@ module Split defined?(params) && params['SPLIT_DISABLE'] end - def begin_experiment(experiment, alternative_name = nil) - warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0' - alternative_name ||= experiment.control.name - ab_user[experiment.key] = alternative_name - alternative_name - end - def ab_user @ab_user ||= User.new(self) end
0
removed deprecated methods
12
.rb
rb
mit
splitrb/split
10072026
<NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); }); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), '<a class="here", href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), '<a class="here", href="">test here test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Insert text into deepest abbreviation node Fixes emmetio/expand-abbreviation#20 <DFF> @@ -14,6 +14,10 @@ describe('Convert token abbreviations', () => { equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); + equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); + equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); + equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); + equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); });
4
Insert text into deepest abbreviation node
0
.ts
ts
mit
emmetio/emmet
10072027
<NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); }); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), '<a class="here", href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), '<a class="here", href="">test here test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Insert text into deepest abbreviation node Fixes emmetio/expand-abbreviation#20 <DFF> @@ -14,6 +14,10 @@ describe('Convert token abbreviations', () => { equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); + equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); + equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); + equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); + equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); });
4
Insert text into deepest abbreviation node
0
.ts
ts
mit
emmetio/emmet
10072028
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end end end describe 'find' do it "should return an existing experiment" do experiment.save experiment = Split::ExperimentCatalog.find('basket_text') expect(experiment.name).to eq('basket_text') end it "should return an existing experiment" do expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil end end describe 'control' do it 'should be the first alternative' do experiment.save end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end context "from configuration" do let(:experiment_name) { :my_experiment } let(:experiments) do { experiment_name => { alternatives: ["Control Opt", "Alt one"] } } end before { Split.configuration.experiments = experiments } it "assigns default values to the experiment" do expect(Split::Experiment.new(experiment_name).resettable).to eq(true) end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> Move specs to appropriate file <DFF> @@ -104,18 +104,6 @@ describe Split::Experiment do end end - describe 'find' do - it "should return an existing experiment" do - experiment.save - experiment = Split::ExperimentCatalog.find('basket_text') - expect(experiment.name).to eq('basket_text') - end - - it "should return an existing experiment" do - expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil - end - end - describe 'control' do it 'should be the first alternative' do experiment.save
0
Move specs to appropriate file
12
.rb
rb
mit
splitrb/split
10072029
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end end end describe 'find' do it "should return an existing experiment" do experiment.save experiment = Split::ExperimentCatalog.find('basket_text') expect(experiment.name).to eq('basket_text') end it "should return an existing experiment" do expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil end end describe 'control' do it 'should be the first alternative' do experiment.save end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end context "from configuration" do let(:experiment_name) { :my_experiment } let(:experiments) do { experiment_name => { alternatives: ["Control Opt", "Alt one"] } } end before { Split.configuration.experiments = experiments } it "assigns default values to the experiment" do expect(Split::Experiment.new(experiment_name).resettable).to eq(true) end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> Move specs to appropriate file <DFF> @@ -104,18 +104,6 @@ describe Split::Experiment do end end - describe 'find' do - it "should return an existing experiment" do - experiment.save - experiment = Split::ExperimentCatalog.find('basket_text') - expect(experiment.name).to eq('basket_text') - end - - it "should return an existing experiment" do - expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil - end - end - describe 'control' do it 'should be the first alternative' do experiment.save
0
Move specs to appropriate file
12
.rb
rb
mit
splitrb/split
10072030
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end end end describe 'find' do it "should return an existing experiment" do experiment.save experiment = Split::ExperimentCatalog.find('basket_text') expect(experiment.name).to eq('basket_text') end it "should return an existing experiment" do expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil end end describe 'control' do it 'should be the first alternative' do experiment.save end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end context "from configuration" do let(:experiment_name) { :my_experiment } let(:experiments) do { experiment_name => { alternatives: ["Control Opt", "Alt one"] } } end before { Split.configuration.experiments = experiments } it "assigns default values to the experiment" do expect(Split::Experiment.new(experiment_name).resettable).to eq(true) end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> Move specs to appropriate file <DFF> @@ -104,18 +104,6 @@ describe Split::Experiment do end end - describe 'find' do - it "should return an existing experiment" do - experiment.save - experiment = Split::ExperimentCatalog.find('basket_text') - expect(experiment.name).to eq('basket_text') - end - - it "should return an existing experiment" do - expect(Split::ExperimentCatalog.find('non_existent_experiment')).to be_nil - end - end - describe 'control' do it 'should be the first alternative' do experiment.save
0
Move specs to appropriate file
12
.rb
rb
mit
splitrb/split
10072031
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split class Experiment attr_accessor :name attr_accessor :goals attr_accessor :alternative_probabilities attr_accessor :metadata attr_reader :alternatives attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? if new_record? start unless Split.configuration.start_manually elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually end persist_experiment_configuration if new_record? || experiment_configuration_has_changed? redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end def new_record? ExperimentCatalog.find(name).nil? end def ==(obj) self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Reduce the calls to Redis when an experiment is saved Check if an experiment is new or its configuration has changed only once <DFF> @@ -81,12 +81,12 @@ module Split if new_record? start unless Split.configuration.start_manually + persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually + persist_experiment_configuration end - persist_experiment_configuration if new_record? || experiment_configuration_has_changed? - redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self
2
Reduce the calls to Redis when an experiment is saved
2
.rb
rb
mit
splitrb/split
10072032
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split class Experiment attr_accessor :name attr_accessor :goals attr_accessor :alternative_probabilities attr_accessor :metadata attr_reader :alternatives attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? if new_record? start unless Split.configuration.start_manually elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually end persist_experiment_configuration if new_record? || experiment_configuration_has_changed? redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end def new_record? ExperimentCatalog.find(name).nil? end def ==(obj) self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Reduce the calls to Redis when an experiment is saved Check if an experiment is new or its configuration has changed only once <DFF> @@ -81,12 +81,12 @@ module Split if new_record? start unless Split.configuration.start_manually + persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually + persist_experiment_configuration end - persist_experiment_configuration if new_record? || experiment_configuration_has_changed? - redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self
2
Reduce the calls to Redis when an experiment is saved
2
.rb
rb
mit
splitrb/split
10072033
<NME> experiment.rb <BEF> # frozen_string_literal: true module Split class Experiment attr_accessor :name attr_accessor :goals attr_accessor :alternative_probabilities attr_accessor :metadata attr_reader :alternatives attr_reader :resettable DEFAULT_OPTIONS = { resettable: true } def self.find(name) Split.cache(:experiments, name) do return unless Split.redis.exists?(name) Experiment.new(name).tap { |exp| exp.load_from_redis } end end def initialize(name, options = {}) options = DEFAULT_OPTIONS.merge(options) @name = name.to_s extract_alternatives_from_options(options) end def self.finished_key(key) "#{key}:finished" end def set_alternatives_and_options(options) options_with_defaults = DEFAULT_OPTIONS.merge( options.reject { |k, v| v.nil? } ) self.alternatives = options_with_defaults[:alternatives] self.goals = options_with_defaults[:goals] self.resettable = options_with_defaults[:resettable] self.algorithm = options_with_defaults[:algorithm] self.metadata = options_with_defaults[:metadata] end def extract_alternatives_from_options(options) alts = options[:alternatives] || [] if alts.length == 1 if alts[0].is_a? Hash alts = alts[0].map { |k, v| { k => v } } end end if alts.empty? exp_config = Split.configuration.experiment_for(name) if exp_config alts = load_alternatives_from_configuration options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration options[:metadata] = load_metadata_from_configuration options[:resettable] = exp_config[:resettable] options[:algorithm] = exp_config[:algorithm] end end options[:alternatives] = alts set_alternatives_and_options(options) # calculate probability that each alternative is the winner @alternative_probabilities = {} alts end def save validate! if new_record? if new_record? start unless Split.configuration.start_manually elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually end persist_experiment_configuration if new_record? || experiment_configuration_has_changed? redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self def validate! if @alternatives.empty? && Split.configuration.experiment_for(@name).nil? raise ExperimentNotFound.new("Experiment #{@name} not found") end @alternatives.each { |a| a.validate! } goals_collection.validate! end def new_record? ExperimentCatalog.find(name).nil? end def ==(obj) self.name == obj.name end def [](name) alternatives.find { |a| a.name == name } end def algorithm @algorithm ||= Split.configuration.algorithm end def algorithm=(algorithm) @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm end def resettable=(resettable) @resettable = resettable.is_a?(String) ? resettable == "true" : resettable end def alternatives=(alts) @alternatives = alts.map do |alternative| if alternative.kind_of?(Split::Alternative) alternative else Split::Alternative.new(alternative, @name) end end end def winner Split.cache(:experiment_winner, name) do experiment_winner = redis.hget(:experiment_winner, name) if experiment_winner Split::Alternative.new(experiment_winner, name) else nil end end end def has_winner? return @has_winner if defined? @has_winner @has_winner = !winner.nil? end def winner=(winner_name) redis.hset(:experiment_winner, name, winner_name.to_s) @has_winner = true Split.configuration.on_experiment_winner_choose.call(self) end def participant_count alternatives.inject(0) { |sum, a| sum + a.participant_count } end def control alternatives.first end def reset_winner redis.hdel(:experiment_winner, name) @has_winner = false Split::Cache.clear_key(@name) end def start redis.hset(:experiment_start_times, @name, Time.now.to_i) end def start_time Split.cache(:experiment_start_times, @name) do t = redis.hget(:experiment_start_times, @name) if t # Check if stored time is an integer if t =~ /^[-+]?[0-9]+$/ Time.at(t.to_i) else Time.parse(t) end end end end def next_alternative winner || random_alternative end def random_alternative if alternatives.length > 1 algorithm.choose_alternative(self) else alternatives.first end end def version @version ||= (redis.get("#{name}:version").to_i || 0) end def increment_version @version = redis.incr("#{name}:version") end def key if version.to_i > 0 "#{name}:#{version}" else name end end def goals_key "#{name}:goals" end def finished_key self.class.finished_key(key) end def metadata_key "#{name}:metadata" end def resettable? resettable end def reset Split.configuration.on_before_experiment_reset.call(self) Split::Cache.clear_key(@name) alternatives.each(&:reset) reset_winner Split.configuration.on_experiment_reset.call(self) increment_version end def delete Split.configuration.on_before_experiment_delete.call(self) if Split.configuration.start_manually redis.hdel(:experiment_start_times, @name) end reset_winner redis.srem(:experiments, name) remove_experiment_cohorting remove_experiment_configuration Split.configuration.on_experiment_delete.call(self) increment_version end def delete_metadata redis.del(metadata_key) end def load_from_redis exp_config = redis.hgetall(experiment_config_key) options = { resettable: exp_config["resettable"], algorithm: exp_config["algorithm"], alternatives: load_alternatives_from_redis, goals: Split::GoalsCollection.new(@name).load_from_redis, metadata: load_metadata_from_redis } set_alternatives_and_options(options) end def calc_winning_alternatives # Cache the winning alternatives so we recalculate them once per the specified interval. intervals_since_epoch = Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval if self.calc_time != intervals_since_epoch if goals.empty? self.estimate_winning_alternative else goals.each do |goal| self.estimate_winning_alternative(goal) end end self.calc_time = intervals_since_epoch self.save end end def estimate_winning_alternative(goal = nil) # initialize a hash of beta distributions based on the alternatives' conversion rates beta_params = calc_beta_params(goal) winning_alternatives = [] Split.configuration.beta_probability_simulations.times do # calculate simulated conversion rates from the beta distributions simulated_cr_hash = calc_simulated_conversion_rates(beta_params) winning_alternative = find_simulated_winner(simulated_cr_hash) # push the winning pair to the winning_alternatives array winning_alternatives.push(winning_alternative) end winning_counts = count_simulated_wins(winning_alternatives) @alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations) write_to_alternatives(goal) self.save end def write_to_alternatives(goal = nil) alternatives.each do |alternative| alternative.set_p_winner(@alternative_probabilities[alternative], goal) end end def calc_alternative_probabilities(winning_counts, number_of_simulations) alternative_probabilities = {} winning_counts.each do |alternative, wins| alternative_probabilities[alternative] = wins / number_of_simulations.to_f end alternative_probabilities end def count_simulated_wins(winning_alternatives) # initialize a hash to keep track of winning alternative in simulations winning_counts = {} alternatives.each do |alternative| winning_counts[alternative] = 0 end # count number of times each alternative won, calculate probabilities, place in hash winning_alternatives.each do |alternative| winning_counts[alternative] += 1 end winning_counts end def find_simulated_winner(simulated_cr_hash) # figure out which alternative had the highest simulated conversion rate winning_pair = ["", 0.0] simulated_cr_hash.each do |alternative, rate| if rate > winning_pair[1] winning_pair = [alternative, rate] end end winner = winning_pair[0] winner end def calc_simulated_conversion_rates(beta_params) simulated_cr_hash = {} # create a hash which has the conversion rate pulled from each alternative's beta distribution beta_params.each do |alternative, params| alpha = params[0] beta = params[1] simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta) simulated_cr_hash[alternative] = simulated_conversion_rate end simulated_cr_hash end def calc_beta_params(goal = nil) beta_params = {} alternatives.each do |alternative| conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal) alpha = 1 + conversions beta = 1 + alternative.participant_count - conversions params = [alpha, beta] beta_params[alternative] = params end beta_params end def calc_time=(time) redis.hset(experiment_config_key, :calc_time, time) end def calc_time redis.hget(experiment_config_key, :calc_time).to_i end def jstring(goal = nil) js_id = if goal.nil? name else name + "-" + goal end js_id.gsub("/", "--") end def cohorting_disabled? @cohorting_disabled ||= begin value = redis.hget(experiment_config_key, :cohorting) value.nil? ? false : value.downcase == "true" end end def disable_cohorting @cohorting_disabled = true redis.hset(experiment_config_key, :cohorting, true.to_s) end def enable_cohorting @cohorting_disabled = false redis.hset(experiment_config_key, :cohorting, false.to_s) end protected def experiment_config_key "experiment_configurations/#{@name}" end def load_metadata_from_configuration Split.configuration.experiment_for(@name)[:metadata] end def load_metadata_from_redis meta = redis.get(metadata_key) JSON.parse(meta) unless meta.nil? end def load_alternatives_from_configuration alts = Split.configuration.experiment_for(@name)[:alternatives] raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts if alts.is_a?(Hash) alts.keys else alts.flatten end end def load_alternatives_from_redis alternatives = redis.lrange(@name, 0, -1) alternatives.map do |alt| alt = begin JSON.parse(alt) rescue alt end Split::Alternative.new(alt, @name) end end private def redis Split.redis end def redis_interface RedisInterface.new end def persist_experiment_configuration redis_interface.add_to_set(:experiments, name) redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json }) goals_collection.save if @metadata redis.set(metadata_key, @metadata.to_json) else delete_metadata end end def remove_experiment_configuration @alternatives.each(&:delete) goals_collection.delete delete_metadata redis.del(@name) end def experiment_configuration_has_changed? existing_experiment = Experiment.find(@name) existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) || existing_experiment.goals != @goals || existing_experiment.metadata != @metadata end def goals_collection Split::GoalsCollection.new(@name, @goals) end def remove_experiment_cohorting @cohorting_disabled = false redis.hdel(experiment_config_key, :cohorting) end end end <MSG> Reduce the calls to Redis when an experiment is saved Check if an experiment is new or its configuration has changed only once <DFF> @@ -81,12 +81,12 @@ module Split if new_record? start unless Split.configuration.start_manually + persist_experiment_configuration elsif experiment_configuration_has_changed? reset unless Split.configuration.reset_manually + persist_experiment_configuration end - persist_experiment_configuration if new_record? || experiment_configuration_has_changed? - redis.hset(experiment_config_key, :resettable, resettable) redis.hset(experiment_config_key, :algorithm, algorithm.to_s) self
2
Reduce the calls to Redis when an experiment is saved
2
.rb
rb
mit
splitrb/split
10072034
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton(ariaHelper) { return { restrict:'E', replace: true, transclude: true, template: setTemplate, link: function(scope, element, attrs) { var btnHasTextContent, node; node = element[0]; if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function (isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { }); } btnHasTextContent = node.textContent.trim(); if (!btnHasTextContent) { ariaHelper.hasAttribute(node, 'aria-label'); } scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { ctrl.$animate.addClass(element, 'disabled'); } }); element.on('$destroy', function () { }; function isAnchorBtn(attrs) { return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { return '<a class="ui button" ng-transclude></a>' } else { return '<button class="ui button" ng-transclude></button>' } } } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> chore(smButton): Improved smButton directive after review <DFF> @@ -6,16 +6,18 @@ angular .directive('smButton', smButton); - function smButton(ariaHelper) { + function smButton() { return { restrict:'E', replace: true, transclude: true, template: setTemplate, - link: function(scope, element, attrs) { - var btnHasTextContent, node; + link: function(scope, element, attrs, ctrl, transclude) { + var node = element[0]; - node = element[0]; + transclude(function(nodes) { + element.append(nodes); + }); if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -26,9 +28,8 @@ angular }); } - btnHasTextContent = node.textContent.trim(); - if (!btnHasTextContent) { - ariaHelper.hasAttribute(node, 'aria-label'); + if (attrs.ariaLabel === void 0) { + element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -40,14 +41,14 @@ angular }; function isAnchorBtn(attrs) { - return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) + return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { - return '<a class="ui button" ng-transclude></a>' + return '<a class="ui button"></a>'; } else { - return '<button class="ui button" ng-transclude></button>' + return '<button class="ui button"></button>'; } } }
11
chore(smButton): Improved smButton directive after review
10
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072035
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton(ariaHelper) { return { restrict:'E', replace: true, transclude: true, template: setTemplate, link: function(scope, element, attrs) { var btnHasTextContent, node; node = element[0]; if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function (isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { }); } btnHasTextContent = node.textContent.trim(); if (!btnHasTextContent) { ariaHelper.hasAttribute(node, 'aria-label'); } scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { ctrl.$animate.addClass(element, 'disabled'); } }); element.on('$destroy', function () { }; function isAnchorBtn(attrs) { return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { return '<a class="ui button" ng-transclude></a>' } else { return '<button class="ui button" ng-transclude></button>' } } } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> chore(smButton): Improved smButton directive after review <DFF> @@ -6,16 +6,18 @@ angular .directive('smButton', smButton); - function smButton(ariaHelper) { + function smButton() { return { restrict:'E', replace: true, transclude: true, template: setTemplate, - link: function(scope, element, attrs) { - var btnHasTextContent, node; + link: function(scope, element, attrs, ctrl, transclude) { + var node = element[0]; - node = element[0]; + transclude(function(nodes) { + element.append(nodes); + }); if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -26,9 +28,8 @@ angular }); } - btnHasTextContent = node.textContent.trim(); - if (!btnHasTextContent) { - ariaHelper.hasAttribute(node, 'aria-label'); + if (attrs.ariaLabel === void 0) { + element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -40,14 +41,14 @@ angular }; function isAnchorBtn(attrs) { - return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) + return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { - return '<a class="ui button" ng-transclude></a>' + return '<a class="ui button"></a>'; } else { - return '<button class="ui button" ng-transclude></button>' + return '<button class="ui button"></button>'; } } }
11
chore(smButton): Improved smButton directive after review
10
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072036
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton(ariaHelper) { return { restrict:'E', replace: true, transclude: true, template: setTemplate, link: function(scope, element, attrs) { var btnHasTextContent, node; node = element[0]; if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function (isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { }); } btnHasTextContent = node.textContent.trim(); if (!btnHasTextContent) { ariaHelper.hasAttribute(node, 'aria-label'); } scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { ctrl.$animate.addClass(element, 'disabled'); } }); element.on('$destroy', function () { }; function isAnchorBtn(attrs) { return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { return '<a class="ui button" ng-transclude></a>' } else { return '<button class="ui button" ng-transclude></button>' } } } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> chore(smButton): Improved smButton directive after review <DFF> @@ -6,16 +6,18 @@ angular .directive('smButton', smButton); - function smButton(ariaHelper) { + function smButton() { return { restrict:'E', replace: true, transclude: true, template: setTemplate, - link: function(scope, element, attrs) { - var btnHasTextContent, node; + link: function(scope, element, attrs, ctrl, transclude) { + var node = element[0]; - node = element[0]; + transclude(function(nodes) { + element.append(nodes); + }); if (isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -26,9 +28,8 @@ angular }); } - btnHasTextContent = node.textContent.trim(); - if (!btnHasTextContent) { - ariaHelper.hasAttribute(node, 'aria-label'); + if (attrs.ariaLabel === void 0) { + element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function(isDisabled) { @@ -40,14 +41,14 @@ angular }; function isAnchorBtn(attrs) { - return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) + return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; } function setTemplate(element, attrs) { if (isAnchorBtn(attrs)) { - return '<a class="ui button" ng-transclude></a>' + return '<a class="ui button"></a>'; } else { - return '<button class="ui button" ng-transclude></button>' + return '<button class="ui button"></button>'; } } }
11
chore(smButton): Improved smButton directive after review
10
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072037
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import pug from '../src/markup/format/pug'; import slim from '../src/markup/format/slim'; import parse from '../src/markup'; import createConfig, { Options } from '../src/config'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}>b'), '<div>\n\t<!-- <b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*2'), '<div>\n\t<!-- <b></b><b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*3'), '<div>\n\t<!-- \n\t<b></b>\n\t<b></b>\n\t<b></b>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); it('self-closing', () => { const xmlStyle = createProfile({ 'output.selfClosingStyle': 'xml' }); const htmlStyle = createProfile({ 'output.selfClosingStyle': 'html' }); const xhtmlStyle = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); }); it('boolean attributes', () => { const compact = createProfile({ 'output.compactBoolean': true }); const noCompact = createProfile({ 'output.compactBoolean': false }); equal(format('p[b.]', noCompact), '<p b="b"></p>'); equal(format('p[b.]', compact), '<p b></p>'); equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); }); it('no formatting', () => { const profile = createProfile({ 'output.format': false }); equal(format('div>p', profile), '<div><p></p></div>'); equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); }); it('format specific nodes', () => { equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), '%ul\n\t%li ${1}\n\t%li ${2}'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); describe('Pug', () => { const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")'); // Use closing slash for XML output format equal(format('input[disabled. foo title=test]', createProfile({ 'output.selfClosingStyle': 'xml' })), 'input(type="text", disabled, foo="", title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a(href="${1}") ${2}'); equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")'); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Ensure proper inline element output in HAML Fixes #446 <DFF> @@ -149,6 +149,9 @@ describe('Format', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); + // https://github.com/emmetio/emmet/issues/446 + equal(format('li>a'), '%li\n\t%a(href="") '); + equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") ');
3
Ensure proper inline element output in HAML
0
.ts
ts
mit
emmetio/emmet
10072038
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import pug from '../src/markup/format/pug'; import slim from '../src/markup/format/slim'; import parse from '../src/markup'; import createConfig, { Options } from '../src/config'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}>b'), '<div>\n\t<!-- <b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*2'), '<div>\n\t<!-- <b></b><b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*3'), '<div>\n\t<!-- \n\t<b></b>\n\t<b></b>\n\t<b></b>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); it('self-closing', () => { const xmlStyle = createProfile({ 'output.selfClosingStyle': 'xml' }); const htmlStyle = createProfile({ 'output.selfClosingStyle': 'html' }); const xhtmlStyle = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); }); it('boolean attributes', () => { const compact = createProfile({ 'output.compactBoolean': true }); const noCompact = createProfile({ 'output.compactBoolean': false }); equal(format('p[b.]', noCompact), '<p b="b"></p>'); equal(format('p[b.]', compact), '<p b></p>'); equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); }); it('no formatting', () => { const profile = createProfile({ 'output.format': false }); equal(format('div>p', profile), '<div><p></p></div>'); equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); }); it('format specific nodes', () => { equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), '%ul\n\t%li ${1}\n\t%li ${2}'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); describe('Pug', () => { const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")'); // Use closing slash for XML output format equal(format('input[disabled. foo title=test]', createProfile({ 'output.selfClosingStyle': 'xml' })), 'input(type="text", disabled, foo="", title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a(href="${1}") ${2}'); equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")'); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Ensure proper inline element output in HAML Fixes #446 <DFF> @@ -149,6 +149,9 @@ describe('Format', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); + // https://github.com/emmetio/emmet/issues/446 + equal(format('li>a'), '%li\n\t%a(href="") '); + equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") ');
3
Ensure proper inline element output in HAML
0
.ts
ts
mit
emmetio/emmet
10072039
<NME> tokenizer.ts <BEF> import { deepStrictEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('basic abbreviations', () => { deepStrictEqual(tokenize('ul>li'), [ { type: 'Literal', value: 'ul', start: 0, end: 2 }, { type: 'Operator', operator: 'child', start: 2, end: 3 }, { type: 'Literal', value: 'li', start: 3, end: 5 } ]); deepStrictEqual(tokenize('ul[title="foo+bar\'str\'" (attr)=bar]{(some > text)}'), [ { type: 'Literal', value: 'ul', start: 0, end: 2 }, { type: 'Bracket', open: true, context: 'attribute', start: 2, end: 3 }, { type: 'Literal', value: 'title', start: 3, end: 8 }, { type: 'Operator', operator: 'equal', start: 8, end: 9 }, { type: 'Quote', single: false, start: 9, end: 10 }, { type: 'Literal', value: 'foo+bar\'str\'', start: 10, end: 22 }, { type: 'Quote', single: false, start: 22, end: 23 }, { type: 'WhiteSpace', start: 23, end: 24, value: ' ' }, { type: 'Bracket', open: true, context: 'group', start: 24, end: 25 }, { type: 'Literal', value: 'attr', start: 25, end: 29 }, { type: 'Bracket', open: false, context: 'group', start: 29, end: 30 }, { type: 'Operator', operator: 'equal', start: 30, end: 31 }, { type: 'Literal', value: 'bar', start: 31, end: 34 }, { type: 'Bracket', open: false, context: 'attribute', start: 34, end: 35 }, { type: 'Bracket', open: true, context: 'expression', start: 35, end: 36 }, { type: 'Literal', value: '(some > text)', start: 36, end: 49 }, { type: 'Bracket', open: false, context: 'expression', start: 49, end: 50 } ]); deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ { type: 'Literal', value: 'h', start: 0, end: 1 }, { type: 'RepeaterNumber', size: 1, reverse: false, base: 1, start: 1, end: 2 }, { type: 'Bracket', open: true, context: 'expression', start: 2, end: 3 }, { type: 'Literal', value: 'some', start: 3, end: 7 }, { type: 'Field', index: 1, name: 'field placeholder', start: 7, end: 29 }, deepStrictEqual(tokenize('div{[}+a{}'), [ { type: 'Literal', value: 'div', start: 0, end: 3 }, { type: 'Bracket', open: true, context: 'expression', start: 3, end: 4 }, { type: 'Literal', value: '[', start: 4, end: 5 }, { type: 'Bracket', open: false, context: 'expression', start: 5, end: 6 }, { type: 'Operator', operator: 'sibling', start: 6, end: 7 }, { type: 'Literal', value: 'a', start: 7, end: 8 }, { type: 'Bracket', open: true, context: 'expression', start: 8, end: 9 }, { type: 'Bracket', open: false, context: 'expression', start: 9, end: 10 } ]); }); it('repeater', () => { deepStrictEqual(tokenize('#sample*3'), [ { type: 'Operator', operator: 'id', start: 0, end: 1 }, { type: 'Literal', value: 'sample', start: 1, end: 7 }, { type: 'Repeater', count: 3, value: 0, implicit: false, start: 7, end: 9 } ]); deepStrictEqual(tokenize('div[foo*3]'), [ { type: 'Literal', value: 'div', start: 0, end: 3 }, { type: 'Bracket', open: true, context: 'attribute', start: 3, end: 4 }, { type: 'Literal', value: 'foo*3', start: 4, end: 9 }, { type: 'Bracket', open: false, context: 'attribute', start: 9, end: 10 } ]); deepStrictEqual(tokenize('({a*2})*3'), [ { type: 'Bracket', open: true, context: 'group', start: 0, end: 1 }, { type: 'Bracket', open: true, context: 'expression', start: 1, end: 2 }, { type: 'Literal', value: 'a*2', start: 2, end: 5 }, { type: 'Bracket', open: false, context: 'expression', start: 5, end: 6 }, { type: 'Bracket', open: false, context: 'group', start: 6, end: 7 }, { type: 'Repeater', count: 3, value: 0, implicit: false, start: 7, end: 9 } ]); }); }); <MSG> Updated syntax to access parent repeater Users can modify repeater number with `@^` modifier (multiple ^ are supported) to access parent repeater as base: `a$*2>b$^*3` Fixes #335, #375 <DFF> @@ -33,7 +33,7 @@ describe('Tokenizer', () => { deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ { type: 'Literal', value: 'h', start: 0, end: 1 }, - { type: 'RepeaterNumber', size: 1, reverse: false, base: 1, start: 1, end: 2 }, + { type: 'RepeaterNumber', size: 1, parent: 0, reverse: false, base: 1, start: 1, end: 2 }, { type: 'Bracket', open: true, context: 'expression', start: 2, end: 3 }, { type: 'Literal', value: 'some', start: 3, end: 7 }, { type: 'Field', index: 1, name: 'field placeholder', start: 7, end: 29 },
1
Updated syntax to access parent repeater
1
.ts
ts
mit
emmetio/emmet
10072040
<NME> tokenizer.ts <BEF> import { deepStrictEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('basic abbreviations', () => { deepStrictEqual(tokenize('ul>li'), [ { type: 'Literal', value: 'ul', start: 0, end: 2 }, { type: 'Operator', operator: 'child', start: 2, end: 3 }, { type: 'Literal', value: 'li', start: 3, end: 5 } ]); deepStrictEqual(tokenize('ul[title="foo+bar\'str\'" (attr)=bar]{(some > text)}'), [ { type: 'Literal', value: 'ul', start: 0, end: 2 }, { type: 'Bracket', open: true, context: 'attribute', start: 2, end: 3 }, { type: 'Literal', value: 'title', start: 3, end: 8 }, { type: 'Operator', operator: 'equal', start: 8, end: 9 }, { type: 'Quote', single: false, start: 9, end: 10 }, { type: 'Literal', value: 'foo+bar\'str\'', start: 10, end: 22 }, { type: 'Quote', single: false, start: 22, end: 23 }, { type: 'WhiteSpace', start: 23, end: 24, value: ' ' }, { type: 'Bracket', open: true, context: 'group', start: 24, end: 25 }, { type: 'Literal', value: 'attr', start: 25, end: 29 }, { type: 'Bracket', open: false, context: 'group', start: 29, end: 30 }, { type: 'Operator', operator: 'equal', start: 30, end: 31 }, { type: 'Literal', value: 'bar', start: 31, end: 34 }, { type: 'Bracket', open: false, context: 'attribute', start: 34, end: 35 }, { type: 'Bracket', open: true, context: 'expression', start: 35, end: 36 }, { type: 'Literal', value: '(some > text)', start: 36, end: 49 }, { type: 'Bracket', open: false, context: 'expression', start: 49, end: 50 } ]); deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ { type: 'Literal', value: 'h', start: 0, end: 1 }, { type: 'RepeaterNumber', size: 1, reverse: false, base: 1, start: 1, end: 2 }, { type: 'Bracket', open: true, context: 'expression', start: 2, end: 3 }, { type: 'Literal', value: 'some', start: 3, end: 7 }, { type: 'Field', index: 1, name: 'field placeholder', start: 7, end: 29 }, deepStrictEqual(tokenize('div{[}+a{}'), [ { type: 'Literal', value: 'div', start: 0, end: 3 }, { type: 'Bracket', open: true, context: 'expression', start: 3, end: 4 }, { type: 'Literal', value: '[', start: 4, end: 5 }, { type: 'Bracket', open: false, context: 'expression', start: 5, end: 6 }, { type: 'Operator', operator: 'sibling', start: 6, end: 7 }, { type: 'Literal', value: 'a', start: 7, end: 8 }, { type: 'Bracket', open: true, context: 'expression', start: 8, end: 9 }, { type: 'Bracket', open: false, context: 'expression', start: 9, end: 10 } ]); }); it('repeater', () => { deepStrictEqual(tokenize('#sample*3'), [ { type: 'Operator', operator: 'id', start: 0, end: 1 }, { type: 'Literal', value: 'sample', start: 1, end: 7 }, { type: 'Repeater', count: 3, value: 0, implicit: false, start: 7, end: 9 } ]); deepStrictEqual(tokenize('div[foo*3]'), [ { type: 'Literal', value: 'div', start: 0, end: 3 }, { type: 'Bracket', open: true, context: 'attribute', start: 3, end: 4 }, { type: 'Literal', value: 'foo*3', start: 4, end: 9 }, { type: 'Bracket', open: false, context: 'attribute', start: 9, end: 10 } ]); deepStrictEqual(tokenize('({a*2})*3'), [ { type: 'Bracket', open: true, context: 'group', start: 0, end: 1 }, { type: 'Bracket', open: true, context: 'expression', start: 1, end: 2 }, { type: 'Literal', value: 'a*2', start: 2, end: 5 }, { type: 'Bracket', open: false, context: 'expression', start: 5, end: 6 }, { type: 'Bracket', open: false, context: 'group', start: 6, end: 7 }, { type: 'Repeater', count: 3, value: 0, implicit: false, start: 7, end: 9 } ]); }); }); <MSG> Updated syntax to access parent repeater Users can modify repeater number with `@^` modifier (multiple ^ are supported) to access parent repeater as base: `a$*2>b$^*3` Fixes #335, #375 <DFF> @@ -33,7 +33,7 @@ describe('Tokenizer', () => { deepStrictEqual(tokenize('h${some${1:field placeholder}}'), [ { type: 'Literal', value: 'h', start: 0, end: 1 }, - { type: 'RepeaterNumber', size: 1, reverse: false, base: 1, start: 1, end: 2 }, + { type: 'RepeaterNumber', size: 1, parent: 0, reverse: false, base: 1, start: 1, end: 2 }, { type: 'Bracket', open: true, context: 'expression', start: 2, end: 3 }, { type: 'Literal', value: 'some', start: 3, end: 7 }, { type: 'Field', index: 1, name: 'field placeholder', start: 7, end: 29 },
1
Updated syntax to access parent repeater
1
.ts
ts
mit
emmetio/emmet
10072041
<NME> models.py <BEF> import os from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User OS_NAMES = ( ("aix", "AIX"), ("beos", "BeOS"), ("debian", "Debian Linux"), ("dos", "DOS"), ("freebsd", "FreeBSD"), ("hpux", "HP/UX"), Neither the name of Ask Solem nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ("solaris", "SUN Solaris"), ("suse", "SuSE Linux"), ("yellowdog", "Yellow Dog Linux"), ) ARCHITECTURES = ( ("alpha", "Alpha"), ("hppa", "HPPA"), ("ix86", "Intel"), ("powerpc", "PowerPC"), ("sparc", "Sparc"), ("ultrasparc", "UltraSparc"), ) UPLOAD_TO = getattr(settings, "DJANGOPYPI_RELEASE_UPLOAD_TO", 'dist') class Classifier(models.Model): name = models.CharField(max_length=255, unique=True) class Meta: verbose_name = _(u"classifier") verbose_name_plural = _(u"classifiers") def __unicode__(self): return self.name class Project(models.Model): name = models.CharField(max_length=255, unique=True) license = models.TextField(blank=True) metadata_version = models.CharField(max_length=64, default=1.0) author = models.CharField(max_length=128, blank=True) home_page = models.URLField(verify_exists=False, blank=True, null=True) download_url = models.CharField(max_length=200, blank=True, null=True) summary = models.TextField(blank=True) description = models.TextField(blank=True) author_email = models.CharField(max_length=255, blank=True) classifiers = models.ManyToManyField(Classifier) owner = models.ForeignKey(User, related_name="projects") updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = _(u"project") verbose_name_plural = _(u"projects") def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('djangopypi-show_links', (), {'dist_name': self.name}) @models.permalink def get_pypi_absolute_url(self): return ('djangopypi-pypi_show_links', (), {'dist_name': self.name}) def get_release(self, version): """Return the release object for version, or None""" try: return self.releases.get(version=version) except Release.DoesNotExist: return None class Release(models.Model): version = models.CharField(max_length=32) distribution = models.FileField(upload_to=UPLOAD_TO) md5_digest = models.CharField(max_length=255, blank=True) platform = models.CharField(max_length=128, blank=True) signature = models.CharField(max_length=128, blank=True) filetype = models.CharField(max_length=255, blank=True) pyversion = models.CharField(max_length=32, blank=True) project = models.ForeignKey(Project, related_name="releases") upload_time = models.DateTimeField(auto_now=True) class Meta: verbose_name = _(u"release") verbose_name_plural = _(u"releases") unique_together = ("project", "version", "platform", "distribution", "pyversion") def __unicode__(self): return u"%s (%s)" % (self.release_name, self.platform) def get_pypi_absolute_url(self): return ('djangopypi-pypi_show_links', (), {'dist_name': self.name}) class Release(models.Model): version = models.CharField(max_length=128) def filename(self): return os.path.basename(self.distribution.name) @property def release_name(self): return u"%s-%s" % (self.project.name, self.version) @property def path(self): return self.distribution.name @models.permalink def get_absolute_url(self): return ('djangopypi-show_version', (), {'dist_name': self.project, 'version': self.version}) def get_dl_url(self): return "%s#md5=%s" % (self.distribution.url, self.md5_digest) def get_dl_url(self): return "%s#md5=%s" % (self.distribution.url, self.md5_digest) <MSG> Added management command for easy_installing into the chishop <DFF> @@ -14,7 +14,7 @@ modification, are permitted provided that the following conditions are met: Neither the name of Ask Solem nor the names of its contributors may be used to endorse or promote products derived from this software without specific -prior written permission. +prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, @@ -104,6 +104,12 @@ class Project(models.Model): def get_pypi_absolute_url(self): return ('djangopypi-pypi_show_links', (), {'dist_name': self.name}) + def get_release(self, version): + """Return the release object for version, or None""" + try: + self.releases.get(version=version) + except Release.DoesNotExist: + return None class Release(models.Model): version = models.CharField(max_length=128) @@ -152,5 +158,3 @@ class Release(models.Model): def get_dl_url(self): return "%s#md5=%s" % (self.distribution.url, self.md5_digest) - -
7
Added management command for easy_installing into the chishop
3
.py
py
bsd-3-clause
ask/chishop
10072042
<NME> .travis.yml <BEF> language: node_js node_js: - 0.10 - 0.11 before_script: - npm install -g gulp script: - gulp test <MSG> chore(project): Update .travis.yml to run with latest nodejs <DFF> @@ -1,11 +1,15 @@ language: node_js node_js: - - 0.10 - - 0.11 - -before_script: - - npm install -g gulp - -script: - - gulp test \ No newline at end of file + - node +env: + - CXX=g++-4.8 +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 +cache: + directories: + - node_modules \ No newline at end of file
12
chore(project): Update .travis.yml to run with latest nodejs
8
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072043
<NME> .travis.yml <BEF> language: node_js node_js: - 0.10 - 0.11 before_script: - npm install -g gulp script: - gulp test <MSG> chore(project): Update .travis.yml to run with latest nodejs <DFF> @@ -1,11 +1,15 @@ language: node_js node_js: - - 0.10 - - 0.11 - -before_script: - - npm install -g gulp - -script: - - gulp test \ No newline at end of file + - node +env: + - CXX=g++-4.8 +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 +cache: + directories: + - node_modules \ No newline at end of file
12
chore(project): Update .travis.yml to run with latest nodejs
8
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072044
<NME> .travis.yml <BEF> language: node_js node_js: - 0.10 - 0.11 before_script: - npm install -g gulp script: - gulp test <MSG> chore(project): Update .travis.yml to run with latest nodejs <DFF> @@ -1,11 +1,15 @@ language: node_js node_js: - - 0.10 - - 0.11 - -before_script: - - npm install -g gulp - -script: - - gulp test \ No newline at end of file + - node +env: + - CXX=g++-4.8 +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 +cache: + directories: + - node_modules \ No newline at end of file
12
chore(project): Update .travis.yml to run with latest nodejs
8
.yml
travis
mit
Semantic-Org/Semantic-UI-Angular
10072045
<NME> output-stream.ts <BEF> import { AbbreviationAttribute, AbbreviationNode } from '@emmetio/abbreviation'; import { Config, Options, StringCase } from './config'; export interface OutputStream { options: Options; value: string; level: number; offset: number; line: number; column: number; } export const expressionStart = '{'; export const expressionEnd = '}'; export default function createOutputStream(options: Options, level = 0): OutputStream { return { options, value: '', level, offset: 0, } /** * Pushes raw string into output stream */ export function push(stream: OutputStream, text: string) { stream.value += text; stream.offset += text.length; stream.column += text.length; } /** * Pushes given string with newline formatting into output */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and // use `pushNewline()` to maintain proper line/column state const lines = splitByLines(value); for (let i = 0, il = lines.length - 1; i <= il; i++) { push(stream, lines[i]); if (i !== il) { pushNewline(stream, true); } } } /** * Pushes new line into given output stream */ export function pushNewline(stream: OutputStream, indent?: boolean | number) { const baseIndent = stream.options['output.baseIndent']; const newline = stream.options['output.newline']; push(stream, newline + baseIndent); stream.line++; stream.column = baseIndent.length; if (indent) { pushIndent(stream, indent === true ? stream.level : indent); } } */ export function pushIndent(stream: OutputStream, size = stream.level) { const indent = stream.options['output.indent']; pushString(stream, indent.repeat(Math.max(size, 0))); } /** } */ export function pushField(stream: OutputStream, index: number, placeholder: string) { const field = stream.options['output.field']; pushString(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); } /** } /** * Returns given tag name formatted according to given config */ export function tagName(name: string, config: Config) { return strCase(name, config.options['output.tagCase']); } /** * Returns given attribute name formatted according to given config */ export function attrName(name: string, config: Config) { return strCase(name, config.options['output.attributeCase']); } /** * Returns character for quoting value of given attribute */ export function attrQuote(attr: AbbreviationAttribute, config: Config, isOpen?: boolean): string { if (attr.valueType === 'expression') { return isOpen ? expressionStart : expressionEnd; } return config.options['output.attributeQuotes'] === 'single' ? '\'' : '"'; } /** * Check if given attribute is boolean */ export function isBooleanAttribute(attr: AbbreviationAttribute, config: Config): boolean { return attr.boolean || config.options['output.booleanAttributes'].includes((attr.name || '').toLowerCase()); } /** * Returns a token for self-closing tag, depending on current options */ export function selfClose(config: Config): string { switch (config.options['output.selfClosingStyle']) { case 'xhtml': return ' /'; case 'xml': return '/'; default: return ''; } } /** * Check if given tag name belongs to inline-level element * @param node Parsed node or tag name */ export function isInline(node: string | AbbreviationNode, config: Config): boolean { if (typeof node === 'string') { return config.options.inlineElements.includes(node.toLowerCase()); } // inline node is a node either with inline-level name or text-only node return node.name ? isInline(node.name, config) : Boolean(node.value && !node.attributes); } /** return text.split(/\r\n|\r|\n/g); } function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase(); function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase(); } return str; } <MSG> Support text processing in output stream <DFF> @@ -22,16 +22,15 @@ export default function createOutputStream(options: Options, level = 0): OutputS } /** - * Pushes raw string into output stream + * Pushes plain string into output stream without newline processing */ export function push(stream: OutputStream, text: string) { - stream.value += text; - stream.offset += text.length; - stream.column += text.length; + const processText = stream.options['output.text']; + _push(stream, processText(text, stream.offset, stream.line, stream.column)); } /** - * Pushes given string with newline formatting into output + * Pushes given string with possible newline formatting into output */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and @@ -65,7 +64,7 @@ export function pushNewline(stream: OutputStream, indent?: boolean | number) { */ export function pushIndent(stream: OutputStream, size = stream.level) { const indent = stream.options['output.indent']; - pushString(stream, indent.repeat(Math.max(size, 0))); + push(stream, indent.repeat(Math.max(size, 0))); } /** @@ -73,7 +72,8 @@ export function pushIndent(stream: OutputStream, size = stream.level) { */ export function pushField(stream: OutputStream, index: number, placeholder: string) { const field = stream.options['output.field']; - pushString(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); + // NB: use `_push` instead of `push` to skip text processing + _push(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); } /** @@ -140,6 +140,15 @@ export function splitByLines(text: string): string[] { return text.split(/\r\n|\r|\n/g); } +/** + * Pushes raw string into output stream without any processing + */ +function _push(stream: OutputStream, text: string) { + stream.value += text; + stream.offset += text.length; + stream.column += text.length; +} + function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase();
16
Support text processing in output stream
7
.ts
ts
mit
emmetio/emmet
10072046
<NME> output-stream.ts <BEF> import { AbbreviationAttribute, AbbreviationNode } from '@emmetio/abbreviation'; import { Config, Options, StringCase } from './config'; export interface OutputStream { options: Options; value: string; level: number; offset: number; line: number; column: number; } export const expressionStart = '{'; export const expressionEnd = '}'; export default function createOutputStream(options: Options, level = 0): OutputStream { return { options, value: '', level, offset: 0, } /** * Pushes raw string into output stream */ export function push(stream: OutputStream, text: string) { stream.value += text; stream.offset += text.length; stream.column += text.length; } /** * Pushes given string with newline formatting into output */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and // use `pushNewline()` to maintain proper line/column state const lines = splitByLines(value); for (let i = 0, il = lines.length - 1; i <= il; i++) { push(stream, lines[i]); if (i !== il) { pushNewline(stream, true); } } } /** * Pushes new line into given output stream */ export function pushNewline(stream: OutputStream, indent?: boolean | number) { const baseIndent = stream.options['output.baseIndent']; const newline = stream.options['output.newline']; push(stream, newline + baseIndent); stream.line++; stream.column = baseIndent.length; if (indent) { pushIndent(stream, indent === true ? stream.level : indent); } } */ export function pushIndent(stream: OutputStream, size = stream.level) { const indent = stream.options['output.indent']; pushString(stream, indent.repeat(Math.max(size, 0))); } /** } */ export function pushField(stream: OutputStream, index: number, placeholder: string) { const field = stream.options['output.field']; pushString(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); } /** } /** * Returns given tag name formatted according to given config */ export function tagName(name: string, config: Config) { return strCase(name, config.options['output.tagCase']); } /** * Returns given attribute name formatted according to given config */ export function attrName(name: string, config: Config) { return strCase(name, config.options['output.attributeCase']); } /** * Returns character for quoting value of given attribute */ export function attrQuote(attr: AbbreviationAttribute, config: Config, isOpen?: boolean): string { if (attr.valueType === 'expression') { return isOpen ? expressionStart : expressionEnd; } return config.options['output.attributeQuotes'] === 'single' ? '\'' : '"'; } /** * Check if given attribute is boolean */ export function isBooleanAttribute(attr: AbbreviationAttribute, config: Config): boolean { return attr.boolean || config.options['output.booleanAttributes'].includes((attr.name || '').toLowerCase()); } /** * Returns a token for self-closing tag, depending on current options */ export function selfClose(config: Config): string { switch (config.options['output.selfClosingStyle']) { case 'xhtml': return ' /'; case 'xml': return '/'; default: return ''; } } /** * Check if given tag name belongs to inline-level element * @param node Parsed node or tag name */ export function isInline(node: string | AbbreviationNode, config: Config): boolean { if (typeof node === 'string') { return config.options.inlineElements.includes(node.toLowerCase()); } // inline node is a node either with inline-level name or text-only node return node.name ? isInline(node.name, config) : Boolean(node.value && !node.attributes); } /** return text.split(/\r\n|\r|\n/g); } function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase(); function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase(); } return str; } <MSG> Support text processing in output stream <DFF> @@ -22,16 +22,15 @@ export default function createOutputStream(options: Options, level = 0): OutputS } /** - * Pushes raw string into output stream + * Pushes plain string into output stream without newline processing */ export function push(stream: OutputStream, text: string) { - stream.value += text; - stream.offset += text.length; - stream.column += text.length; + const processText = stream.options['output.text']; + _push(stream, processText(text, stream.offset, stream.line, stream.column)); } /** - * Pushes given string with newline formatting into output + * Pushes given string with possible newline formatting into output */ export function pushString(stream: OutputStream, value: string) { // If given value contains newlines, we should push content line-by-line and @@ -65,7 +64,7 @@ export function pushNewline(stream: OutputStream, indent?: boolean | number) { */ export function pushIndent(stream: OutputStream, size = stream.level) { const indent = stream.options['output.indent']; - pushString(stream, indent.repeat(Math.max(size, 0))); + push(stream, indent.repeat(Math.max(size, 0))); } /** @@ -73,7 +72,8 @@ export function pushIndent(stream: OutputStream, size = stream.level) { */ export function pushField(stream: OutputStream, index: number, placeholder: string) { const field = stream.options['output.field']; - pushString(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); + // NB: use `_push` instead of `push` to skip text processing + _push(stream, field(index, placeholder, stream.offset, stream.line, stream.column)); } /** @@ -140,6 +140,15 @@ export function splitByLines(text: string): string[] { return text.split(/\r\n|\r|\n/g); } +/** + * Pushes raw string into output stream without any processing + */ +function _push(stream: OutputStream, text: string) { + stream.value += text; + stream.offset += text.length; + stream.column += text.length; +} + function strCase(str: string, type: StringCase) { if (type) { return type === 'upper' ? str.toUpperCase() : str.toLowerCase();
16
Support text processing in output stream
7
.ts
ts
mit
emmetio/emmet
10072047
<NME> utils.ts <BEF> import StreamReader from './index'; const SINGLE_QUOTE = 39; // ' const DOUBLE_QUOTE = 34; // " interface QuotedOptions { /** A character code of quote-escape symbol */ escape?: number; /** Throw error if quotes string can’t be properly consumed */ throws?: boolean; } const defaultQuotedOptions: QuotedOptions = { escape: 92, // \ character throws: false }; /** * Check if given code is a number */ export function isNumber(code: number): boolean { return code > 47 && code < 58; } /** * Check if given character code is alpha code (letter through A to Z) */ export function isAlpha(code: number, from?: number, to?: number): boolean { from = from || 65; // A to = to || 90; // Z code &= ~32; // quick hack to convert any char code to uppercase char code return code >= from && code <= to; } /** * Check if given character code is alpha-numeric (letter through A to Z or number) */ export function isAlphaNumeric(code: number): boolean { return isNumber(code) || isAlpha(code); } export function isAlphaNumericWord(code: number): boolean { return isNumber(code) || isAlphaWord(code); } export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } /** * Check if given character code is a white-space character: a space character * or line breaks */ export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ || code === 160; /* non-breaking space */ } /** * Check if given character code is a space character */ export function isSpace(code: number): boolean { return isWhiteSpace(code) || code === 10 /* LF */ || code === 13; /* CR */ * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); if (stream.eat(isQuote)) { while (!stream.eof()) { switch (stream.next()) { case quote: stream.start = start; return true; case options.escape: stream.next(); break; } } // If we’re here then stream wasn’t properly consumed. // Revert stream and decide what to do stream.pos = start; if (options.throws) { throw stream.error('Unable to consume quoted string'); } } * Check if given character code is a quote character */ export function isQuote(code: number): boolean { return code === SINGLE_QUOTE || code === DOUBLE_QUOTE; } /** return code === 39 /* ' */ || code === 34 /* " */; } * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ export function eatPair(stream: StreamReader, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; if (stream.eat(open)) { let stack = 1; let ch: number; while (!stream.eof()) { if (eatQuoted(stream, options)) { continue; } ch = stream.next()!; if (ch === open) { stack++; } else if (ch === close) { stack--; if (!stack) { stream.start = start; return true; } } else if (ch === options.escape) { stream.next(); } } // If we’re here then paired character can’t be consumed stream.pos = start; if (options.throws) { throw stream.error(`Unable to find matching pair for ${String.fromCharCode(open)}`); } } return false; } <MSG> Renamed stream-reader to scanner <DFF> @@ -1,7 +1,4 @@ -import StreamReader from './index'; - -const SINGLE_QUOTE = 39; // ' -const DOUBLE_QUOTE = 34; // " +import Scanner from './index'; interface QuotedOptions { /** A character code of quote-escape symbol */ @@ -69,7 +66,7 @@ export function isSpace(code: number): boolean { * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ -export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolean { +export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); @@ -103,7 +100,7 @@ export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolea * Check if given character code is a quote character */ export function isQuote(code: number): boolean { - return code === SINGLE_QUOTE || code === DOUBLE_QUOTE; + return code === 39 /* ' */ || code === 34 /* " */; } /** @@ -113,7 +110,7 @@ export function isQuote(code: number): boolean { * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ -export function eatPair(stream: StreamReader, open: number, close: number, options?: QuotedOptions): boolean { +export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos;
4
Renamed stream-reader to scanner
7
.ts
ts
mit
emmetio/emmet
10072048
<NME> utils.ts <BEF> import StreamReader from './index'; const SINGLE_QUOTE = 39; // ' const DOUBLE_QUOTE = 34; // " interface QuotedOptions { /** A character code of quote-escape symbol */ escape?: number; /** Throw error if quotes string can’t be properly consumed */ throws?: boolean; } const defaultQuotedOptions: QuotedOptions = { escape: 92, // \ character throws: false }; /** * Check if given code is a number */ export function isNumber(code: number): boolean { return code > 47 && code < 58; } /** * Check if given character code is alpha code (letter through A to Z) */ export function isAlpha(code: number, from?: number, to?: number): boolean { from = from || 65; // A to = to || 90; // Z code &= ~32; // quick hack to convert any char code to uppercase char code return code >= from && code <= to; } /** * Check if given character code is alpha-numeric (letter through A to Z or number) */ export function isAlphaNumeric(code: number): boolean { return isNumber(code) || isAlpha(code); } export function isAlphaNumericWord(code: number): boolean { return isNumber(code) || isAlphaWord(code); } export function isAlphaWord(code: number): boolean { return code === 95 /* _ */ || isAlpha(code); } /** * Check if given character code is a white-space character: a space character * or line breaks */ export function isWhiteSpace(code: number) { return code === 32 /* space */ || code === 9 /* tab */ || code === 160; /* non-breaking space */ } /** * Check if given character code is a space character */ export function isSpace(code: number): boolean { return isWhiteSpace(code) || code === 10 /* LF */ || code === 13; /* CR */ * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); if (stream.eat(isQuote)) { while (!stream.eof()) { switch (stream.next()) { case quote: stream.start = start; return true; case options.escape: stream.next(); break; } } // If we’re here then stream wasn’t properly consumed. // Revert stream and decide what to do stream.pos = start; if (options.throws) { throw stream.error('Unable to consume quoted string'); } } * Check if given character code is a quote character */ export function isQuote(code: number): boolean { return code === SINGLE_QUOTE || code === DOUBLE_QUOTE; } /** return code === 39 /* ' */ || code === 34 /* " */; } * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ export function eatPair(stream: StreamReader, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; if (stream.eat(open)) { let stack = 1; let ch: number; while (!stream.eof()) { if (eatQuoted(stream, options)) { continue; } ch = stream.next()!; if (ch === open) { stack++; } else if (ch === close) { stack--; if (!stack) { stream.start = start; return true; } } else if (ch === options.escape) { stream.next(); } } // If we’re here then paired character can’t be consumed stream.pos = start; if (options.throws) { throw stream.error(`Unable to find matching pair for ${String.fromCharCode(open)}`); } } return false; } <MSG> Renamed stream-reader to scanner <DFF> @@ -1,7 +1,4 @@ -import StreamReader from './index'; - -const SINGLE_QUOTE = 39; // ' -const DOUBLE_QUOTE = 34; // " +import Scanner from './index'; interface QuotedOptions { /** A character code of quote-escape symbol */ @@ -69,7 +66,7 @@ export function isSpace(code: number): boolean { * @return `true` if quoted string was consumed. The contents of quoted string * will be available as `stream.current()` */ -export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolean { +export function eatQuoted(stream: Scanner, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos; const quote = stream.peek(); @@ -103,7 +100,7 @@ export function eatQuoted(stream: StreamReader, options?: QuotedOptions): boolea * Check if given character code is a quote character */ export function isQuote(code: number): boolean { - return code === SINGLE_QUOTE || code === DOUBLE_QUOTE; + return code === 39 /* ' */ || code === 34 /* " */; } /** @@ -113,7 +110,7 @@ export function isQuote(code: number): boolean { * @return Returns `true` if character pair was successfully consumed, it’s * content will be available as `stream.current()` */ -export function eatPair(stream: StreamReader, open: number, close: number, options?: QuotedOptions): boolean { +export function eatPair(stream: Scanner, open: number, close: number, options?: QuotedOptions): boolean { options = { ...defaultQuotedOptions, ...options }; const start = stream.pos;
4
Renamed stream-reader to scanner
7
.ts
ts
mit
emmetio/emmet
10072049
<NME> .npmignore <BEF> npm-debug.log* node_modules jspm_packages .npm /.* /*.* /test /src /packages <MSG> Exclude snippets from publishing <DFF> @@ -7,3 +7,4 @@ jspm_packages /test /src /packages +/snippets
1
Exclude snippets from publishing
0
npmignore
mit
emmetio/emmet