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
|
---|---|---|---|---|---|---|---|---|
10069250 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069251 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069252 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069253 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069254 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069255 | <NME> TextAreaInputHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using AvaloniaEdit.Utils;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// A set of input bindings and event handlers for the text area.
/// </summary>
/// <remarks>
/// <para>
/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
/// a number of active stacked input handlers.
/// </para>
/// <para>
/// The text area also stores a reference to a default input handler, but that is not necessarily active.
/// </para>
/// <para>
/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
/// They are detached in the reverse order of being attached.
/// </para>
/// </remarks>
public interface ITextAreaInputHandler
{
/// <summary>
/// Gets the text area that the input handler belongs to.
/// </summary>
TextArea TextArea
{
get;
}
/// <summary>
/// Attaches an input handler to the text area.
/// </summary>
void Attach();
/// <summary>
/// Detaches the input handler from the text area.
/// </summary>
void Detach();
}
/// <summary>
/// Stacked input handler.
/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
/// </summary>
public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
{
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
protected TextAreaStackedInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <inheritdoc/>
public virtual void Attach()
{
}
/// <inheritdoc/>
public virtual void Detach()
{
}
/// <summary>
/// Called for the PreviewKeyDown event.
/// </summary>
public virtual void OnPreviewKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called for the PreviewKeyUp event.
/// </summary>
public virtual void OnPreviewKeyUp(KeyEventArgs e)
{
}
}
/// <summary>
/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public class TextAreaInputHandler : ITextAreaInputHandler
{
private readonly ObserveAddRemoveCollection<RoutedCommandBinding> _commandBindings;
private readonly List<KeyBinding> _keyBindings;
private readonly ObserveAddRemoveCollection<ITextAreaInputHandler> _nestedInputHandlers;
/// <summary>
/// Creates a new TextAreaInputHandler.
/// </summary>
public TextAreaInputHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
_commandBindings = new ObserveAddRemoveCollection<RoutedCommandBinding>(CommandBinding_Added, CommandBinding_Removed);
_keyBindings = new List<KeyBinding>();
_nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
}
/// <inheritdoc/>
public TextArea TextArea { get; }
/// <summary>
/// Gets whether the input handler is currently attached to the text area.
/// </summary>
public bool IsAttached { get; private set; }
#region CommandBindings / KeyBindings
/// <summary>
/// Gets the command bindings of this input handler.
/// </summary>
public ICollection<RoutedCommandBinding> CommandBindings => _commandBindings;
private void CommandBinding_Added(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Add(commandBinding);
}
private void CommandBinding_Removed(RoutedCommandBinding commandBinding)
{
if (IsAttached)
TextArea.CommandBindings.Remove(commandBinding);
}
/// <summary>
/// Gets the input bindings of this input handler.
/// </summary>
public ICollection<KeyBinding> KeyBindings => _keyBindings;
//private void KeyBinding_Added(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Add(keyBinding);
//}
//private void KeyBinding_Removed(KeyBinding keyBinding)
//{
// if (IsAttached)
// TextArea.KeyBindings.Remove(keyBinding);
//}
/// <summary>
/// Adds a command and input binding.
/// </summary>
/// <param name="command">The command ID.</param>
/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
/// <param name="key">The key of the keyboard shortcut.</param>
/// <param name="handler">The event handler to run when the command is executed.</param>
public void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(new KeyBinding { Command = command, Gesture = new KeyGesture (key, modifiers) });
}
#endregion
#region NestedInputHandlers
/// <summary>
/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
/// together with this input handler.
/// </summary>
public ICollection<ITextAreaInputHandler> NestedInputHandlers => _nestedInputHandlers;
private void NestedInputHandler_Added(ITextAreaInputHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
if (handler.TextArea != TextArea)
throw new ArgumentException("The nested handler must be working for the same text area!");
if (IsAttached)
handler.Attach();
}
private void NestedInputHandler_Removed(ITextAreaInputHandler handler)
{
if (IsAttached)
handler.Detach();
}
// workaround since InputElement.KeyBindings can't be marked as handled
private void TextAreaOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
foreach (var keyBinding in _keyBindings)
{
if (keyEventArgs.Handled)
{
break;
}
keyBinding.TryHandle(keyEventArgs);
}
}
#endregion
#region Attach/Detach
/// <inheritdoc/>
public virtual void Attach()
{
if (IsAttached)
throw new InvalidOperationException("Input handler is already attached");
IsAttached = true;
TextArea.CommandBindings.AddRange(_commandBindings);
TextArea.KeyDown += TextAreaOnKeyDown;
//TextArea.KeyBindings.AddRange(_keyBindings);
foreach (var handler in _nestedInputHandlers)
handler.Attach();
}
/// <inheritdoc/>
public virtual void Detach()
{
if (!IsAttached)
throw new InvalidOperationException("Input handler is not attached");
IsAttached = false;
foreach (var b in _commandBindings)
TextArea.CommandBindings.Remove(b);
TextArea.KeyDown -= TextAreaOnKeyDown;
//foreach (var b in _keyBindings)
// TextArea.KeyBindings.Remove(b);
foreach (var handler in _nestedInputHandlers)
handler.Detach();
}
#endregion
}
}
<MSG> Better handling of gestures in RoutedCommand
<DFF> @@ -215,6 +215,16 @@ namespace AvaloniaEdit.Editing
keyBinding.TryHandle(keyEventArgs);
}
+
+ foreach (var commandBinding in CommandBindings)
+ {
+ if (commandBinding.Command.Gesture?.Matches(keyEventArgs) == true)
+ {
+ commandBinding.Command.Execute(null, (IInputElement)sender);
+ keyEventArgs.Handled = true;
+ break;
+ }
+ }
}
#endregion
| 10 | Better handling of gestures in RoutedCommand | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10069256 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); }); var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Support Promise/A to be returned from controller methods <DFF> @@ -2512,4 +2512,136 @@ $(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); + + + module("controller promise"); + + asyncTest("should support jQuery promise success callback", 1, function() { + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + var d = $.Deferred(); + + setTimeout(function() { + d.resolve(data); + start(); + }); + + return d.promise(); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) { + equal(result, data, "data provided to done callback"); + }); + }); + + asyncTest("should support jQuery promise fail callback", 1, function() { + var failArgs = {}; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + var d = $.Deferred(); + + setTimeout(function() { + d.reject(failArgs); + start(); + }); + + return d.promise(); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.fail(function(result) { + equal(result, failArgs, "fail args provided to fail callback"); + }); + }); + + asyncTest("should support JS promise success callback", 1, function() { + if(!Promise) { + ok(true, "Promise not supported"); + return; + } + + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return new Promise(function(resolve, reject) { + setTimeout(function() { + resolve(data); + start(); + }); + }); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) { + equal(result, data, "data provided to done callback"); + }); + }); + + asyncTest("should support JS promise fail callback", 1, function() { + if(!Promise) { + ok(true, "Promise not supported"); + return; + } + + var failArgs = {}; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return new Promise(function(resolve, reject) { + setTimeout(function() { + reject(failArgs); + start(); + }); + }); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.fail(function(result) { + equal(result, failArgs, "fail args provided to fail callback"); + }); + }); + + test("should support non-promise result", 1, function() { + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return data; + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) | 132 | Core: Support Promise/A to be returned from controller methods | 0 | .js | tests | mit | tabalinas/jsgrid |
10069257 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); }); var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Support Promise/A to be returned from controller methods <DFF> @@ -2512,4 +2512,136 @@ $(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); + + + module("controller promise"); + + asyncTest("should support jQuery promise success callback", 1, function() { + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + var d = $.Deferred(); + + setTimeout(function() { + d.resolve(data); + start(); + }); + + return d.promise(); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) { + equal(result, data, "data provided to done callback"); + }); + }); + + asyncTest("should support jQuery promise fail callback", 1, function() { + var failArgs = {}; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + var d = $.Deferred(); + + setTimeout(function() { + d.reject(failArgs); + start(); + }); + + return d.promise(); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.fail(function(result) { + equal(result, failArgs, "fail args provided to fail callback"); + }); + }); + + asyncTest("should support JS promise success callback", 1, function() { + if(!Promise) { + ok(true, "Promise not supported"); + return; + } + + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return new Promise(function(resolve, reject) { + setTimeout(function() { + resolve(data); + start(); + }); + }); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) { + equal(result, data, "data provided to done callback"); + }); + }); + + asyncTest("should support JS promise fail callback", 1, function() { + if(!Promise) { + ok(true, "Promise not supported"); + return; + } + + var failArgs = {}; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return new Promise(function(resolve, reject) { + setTimeout(function() { + reject(failArgs); + start(); + }); + }); + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.fail(function(result) { + equal(result, failArgs, "fail args provided to fail callback"); + }); + }); + + test("should support non-promise result", 1, function() { + var data = []; + var gridOptions = { + autoload: false, + controller: { + loadData: function() { + return data; + } + } + }; + + var grid = new Grid($("#jsGrid"), gridOptions); + + var promise = grid._controllerCall("loadData", {}, false, $.noop); + promise.done(function(result) | 132 | Core: Support Promise/A to be returned from controller methods | 0 | .js | tests | mit | tabalinas/jsgrid |
10069258 | <NME> jsgrid.tests.js
<BEF> $(function() {
var Grid = jsGrid.Grid,
JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID;
Grid.prototype.updateOnResize = false;
module("basic");
test("default creation", function() {
var gridOptions = {
simpleOption: "test",
complexOption: {
a: "subtest",
b: 1,
c: {}
}
},
grid = new Grid("#jsGrid", gridOptions);
equal(grid._container[0], $("#jsGrid")[0], "container saved");
equal(grid.simpleOption, "test", "primitive option extended");
equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended");
});
test("jquery adapter creation", function() {
var gridOptions = {
option: "test"
},
$element = $("#jsGrid"),
result = $element.jsGrid(gridOptions),
grid = $element.data(JSGRID_DATA_KEY);
equal(result, $element, "jquery fn returned source jQueryElement");
ok(grid instanceof Grid, "jsGrid saved to jquery data");
equal(grid.option, "test", "options provided");
});
test("destroy", function() {
var $element = $("#jsGrid"),
grid;
$element.jsGrid({});
grid = $element.data(JSGRID_DATA_KEY);
grid.destroy();
strictEqual($element.html(), "", "content is removed");
strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed");
});
test("jquery adapter second call changes option value", function() {
var $element = $("#jsGrid"),
gridOptions = {
option: "test"
},
grid;
$element.jsGrid(gridOptions);
grid = $element.data(JSGRID_DATA_KEY);
gridOptions.option = "new test";
$element.jsGrid(gridOptions);
equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed");
equal(grid.option, "new test", "option changed");
});
test("jquery adapter invokes jsGrid method", function() {
var methodResult = "",
$element = $("#jsGrid"),
gridOptions = {
method: function(str) {
methodResult = "test_" + str;
}
};
$element.jsGrid(gridOptions);
$element.jsGrid("method", "invoke");
equal(methodResult, "test_invoke", "method invoked");
});
test("onInit callback", function() {
var $element = $("#jsGrid"),
onInitArguments,
gridOptions = {
onInit: function(args) {
onInitArguments = args;
}
};
var grid = new Grid($element, gridOptions);
equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments");
});
test("controller methods are $.noop when not specified", function() {
var $element = $("#jsGrid"),
gridOptions = {
controller: {}
},
testOption;
$element.jsGrid(gridOptions);
deepEqual($element.data(JSGRID_DATA_KEY)._controller, {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
}, "controller has stub methods");
});
test("option method", function() {
var $element = $("#jsGrid"),
gridOptions = {
test: "value"
},
testOption;
$element.jsGrid(gridOptions);
testOption = $element.jsGrid("option", "test");
equal(testOption, "value", "read option value");
$element.jsGrid("option", "test", "new_value");
testOption = $element.jsGrid("option", "test");
equal(testOption, "new_value", "set option value");
});
test("fieldOption method", function() {
var dataLoadedCount = 0;
var $element = $("#jsGrid"),
gridOptions = {
loadMessage: "",
autoload: true,
controller: {
loadData: function() {
dataLoadedCount++;
return [{ prop1: "value1", prop2: "value2", prop3: "value3" }];
}
},
fields: [
{ name: "prop1", title: "_" }
]
};
$element.jsGrid(gridOptions);
var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name");
equal(fieldOptionValue, "prop1", "read field option");
$element.jsGrid("fieldOption", "prop1", "name", "prop2");
equal($element.text(), "_value2", "set field option by field name");
equal(dataLoadedCount, 1, "data not reloaded on field option change");
$element.jsGrid("fieldOption", 0, "name", "prop3");
equal($element.text(), "_value3", "set field option by field index");
});
test("option changing event handlers", function() {
var $element = $("#jsGrid"),
optionChangingEventArgs,
optionChangedEventArgs,
gridOptions = {
test: "testValue",
another: "anotherValue",
onOptionChanging: function(e) {
optionChangingEventArgs = $.extend({}, e);
e.option = "another";
e.newValue = e.newValue + "_" + this.another;
},
onOptionChanged: function(e) {
optionChangedEventArgs = $.extend({}, e);
}
},
anotherOption;
$element.jsGrid(gridOptions);
$element.jsGrid("option", "test", "newTestValue");
equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging");
equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging");
equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging");
anotherOption = $element.jsGrid("option", "another");
equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value");
equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged");
equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged");
});
test("common layout rendering", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {}),
$headerGrid,
$headerGridTable,
$bodyGrid,
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header");
ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body");
ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container");
$headerGrid = $element.children().eq(0);
$headerGridTable = $headerGrid.children().first();
ok($headerGridTable.hasClass(grid.tableClass), "header table");
equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row");
equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row");
equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row");
ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class");
ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class");
ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class");
$bodyGrid = $element.children().eq(1);
$bodyGridTable = $bodyGrid.children().first();
ok($bodyGridTable.hasClass(grid.tableClass), "body table");
equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table");
equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row");
equal($bodyGridTable.text(), grid.noDataContent, "no data text");
});
test("set default options with setDefaults", function() {
jsGrid.setDefaults({
defaultOption: "test"
});
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "defaultOption"), "test", "default option set");
});
module("loading");
test("loading with controller", function() {
var $element = $("#jsGrid"),
data = [
{ test: "test1" },
{ test: "test2" }
],
gridOptions = {
controller: {
loadData: function() {
return data;
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(grid.option("data"), data, "loadData loads data");
});
test("loadData throws exception when controller method not found", function() {
var $element = $("#jsGrid");
var grid = new Grid($element);
grid._controller = {};
throws(function() {
grid.loadData();
}, /loadData/, "loadData threw an exception");
});
test("onError event should be fired on controller fail", function() {
var errorArgs,
errorFired = 0,
$element = $("#jsGrid"),
gridOptions = {
controller: {
loadData: function() {
return $.Deferred().reject({ value: 1 }, "test").promise();
}
},
onError: function(args) {
errorFired++;
errorArgs = args;
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(errorFired, 1, "onError handler fired");
deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params");
});
asyncTest("autoload should call loadData after render", 1, function() {
new Grid($("#jsGrid"), {
autoload: true,
controller: {
loadData: function() {
ok(true, "autoload calls loadData on creation");
start();
return [];
}
}
});
});
test("loading filtered data", function() {
var filteredData,
loadingArgs,
loadedArgs,
$element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
filtering: true,
fields: [
{
name: "field",
filterValue: function(value) {
return "test";
}
}
],
onDataLoading: function(e) {
loadingArgs = $.extend(true, {}, e);
},
onDataLoaded: function(e) {
loadedArgs = $.extend(true, {}, e);
},
controller: {
loadData: function(filter) {
filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(loadingArgs.filter.field, "test");
equal(grid.option("data").length, 2, "filtered data loaded");
deepEqual(loadedArgs.data, filteredData);
});
asyncTest("loading indication", function() {
var timeout = 10,
stage = "initial",
$element = $("#jsGrid"),
gridOptions = {
loadIndication: true,
loadIndicationDelay: timeout,
loadMessage: "loading...",
loadIndicator: function(config) {
equal(config.message, gridOptions.loadMessage, "message provided");
ok(config.container.jquery, "grid container is provided");
return {
show: function() {
stage = "started";
},
hide: function() {
stage = "finished";
}
};
},
fields: [
{ name: "field" }
],
controller: {
loadData: function() {
var deferred = $.Deferred();
equal(stage, "initial", "initial stage");
setTimeout(function() {
equal(stage, "started", "loading started");
deferred.resolve([]);
equal(stage, "finished", "loading finished");
start();
}, timeout);
return deferred.promise();
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
});
asyncTest("loadingIndication=false should not show loading", 0, function() {
var $element = $("#jsGrid"),
timeout = 10,
gridOptions = {
loadIndication: false,
loadIndicationDelay: timeout,
loadIndicator: function() {
return {
show: function() {
ok(false, "should not call show");
},
hide: function() {
ok(false, "should not call hide");
}
};
},
fields: [
{ name: "field" }
],
controller: {
loadData: function() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve([]);
start();
}, timeout);
return deferred.promise();
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
});
test("search", function() {
var $element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
pageIndex: 2,
_sortField: "field",
_sortOrder: "desc",
filtering: true,
fields: [
{
name: "field",
filterValue: function(value) {
return "test";
}
}
],
controller: {
loadData: function(filter) {
var filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.search();
equal(grid.option("data").length, 2, "data filtered");
strictEqual(grid.option("pageIndex"), 1, "pageIndex reset");
strictEqual(grid._sortField, null, "sortField reset");
strictEqual(grid._sortOrder, "asc", "sortOrder reset");
});
test("change loadStrategy on the fly", function() {
var $element = $("#jsGrid");
var gridOptions = {
controller: {
loadData: function() {
return [];
}
}
};
var grid = new Grid($element, gridOptions);
grid.option("loadStrategy", {
firstDisplayIndex: function() {
return 0;
},
lastDisplayIndex: function() {
return 1;
},
loadParams: function() {
return [];
},
finishLoad: function() {
grid.option("data", [{}]);
}
});
grid.loadData();
equal(grid.option("data").length, 1, "new load strategy is applied");
});
module("filtering");
test("filter rendering", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
fields: [
{
name: "test",
align: "right",
filtercss: "filter-class",
filterTemplate: function() {
var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached");
equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered");
equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field");
});
test("filter get/clear", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
controller: {
loadData: function() {
return [];
}
},
fields: [
{
name: "field",
filterTemplate: function() {
return this.filterControl = $("<input>").attr("type", "text");
},
filterValue: function() {
return this.filterControl.val();
}
}
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test");
deepEqual(grid.getFilter(), { field: "test" }, "get filter");
grid.clearFilter();
deepEqual(grid.getFilter(), { field: "" }, "filter cleared");
equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared");
});
test("field without filtering", function() {
var $element = $("#jsGrid"),
jsGridFieldConfig = {
filterTemplate: function() {
var result = this.filterControl = $("<input>").attr("type", "text");
return result;
},
filterValue: function(value) {
if(!arguments.length) {
return this.filterControl.val();
}
this.filterControl.val(value);
}
},
gridOptions = {
filtering: true,
fields: [
$.extend({}, jsGridFieldConfig, {
name: "field1",
filtering: false
}),
$.extend({}, jsGridFieldConfig, {
name: "field2"
})
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test1");
grid.fields[1].filterControl.val("test2");
deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter");
});
test("search with filter", function() {
var $element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
fields: [
{
name: "field"
}
],
controller: {
loadData: function(filter) {
var filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.search({ field: "test" });
equal(grid.option("data").length, 2, "data filtered");
});
test("filtering with static data should not do actual filtering", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
fields: [
{ type: "text", name: "field" }
],
data: [
{ name: "value1" },
{ name: "value2" }
]
},
grid = new Grid($element, gridOptions);
grid._filterRow.find("input").val("1");
grid.search();
equal(grid.option("data").length, 2, "data is not filtered");
});
module("nodatarow");
test("nodatarow after bind on empty array", function() {
var $element = $("#jsGrid"),
gridOptions = {},
grid = new Grid($element, gridOptions);
grid.option("data", []);
equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered");
equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached");
equal(grid._content.text(), grid.noDataContent, "no data text rendered");
});
test("nodatarow customize content", function() {
var noDataMessage = "NoData Custom Content",
$element = $("#jsGrid"),
gridOptions = {
noDataContent: function() {
return noDataMessage;
}
},
grid = new Grid($element, gridOptions);
grid.option("data", []);
equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached");
equal(grid._content.text(), noDataMessage, "custom noDataContent");
});
module("row rendering", {
setup: function() {
this.testData = [
{ id: 1, text: "test1" },
{ id: 2, text: "test2" },
{ id: 3, text: "test3" }
];
}
});
test("rows rendered correctly", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData
},
grid = new Grid($element, gridOptions);
equal(grid._content.children().length, 3, "rows rendered");
equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items");
equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items");
});
test("custom rowClass", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData,
rowClass: "custom-row-cls"
},
grid = new Grid($element, gridOptions);
equal(grid._content.find("." + grid.oddRowClass).length, 2);
equal(grid._content.find("." + grid.evenRowClass).length, 1);
equal(grid._content.find(".custom-row-cls").length, 3, "custom row class");
});
test("custom rowClass callback", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData,
rowClass: function(item, index) {
return item.text;
}
},
grid = new Grid($element, gridOptions);
equal(grid._content.find("." + grid.oddRowClass).length, 2);
equal(grid._content.find("." + grid.evenRowClass).length, 1);
equal(grid._content.find(".test1").length, 1, "custom row class");
equal(grid._content.find(".test2").length, 1, "custom row class");
equal(grid._content.find(".test3").length, 1, "custom row class");
});
test("rowClick standard handler", function() {
var $element = $("#jsGrid"),
$secondRow,
grid = new Grid($element, { editing: true });
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("click", $.Event($secondRow));
equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow");
});
test("rowClick handler", function() {
var rowClickArgs,
$element = $("#jsGrid"),
$secondRow,
gridOptions = {
rowClick: function(args) {
rowClickArgs = args;
}
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("click", $.Event($secondRow));
ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg");
equal(rowClickArgs.item, this.testData[1], "item arg");
equal(rowClickArgs.itemIndex, 1, "itemIndex arg");
});
test("row selecting with selectedRowClass", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
selecting: true
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("mouseenter", $.Event($secondRow));
ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass");
$secondRow.trigger("mouseleave", $.Event($secondRow));
ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass");
});
test("no row selecting while selection is disabled", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
selecting: false
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("mouseenter", $.Event($secondRow));
ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass");
});
test("refreshing and refreshed callbacks", function() {
var refreshingEventArgs,
refreshedEventArgs,
$element = $("#jsGrid"),
grid = new Grid($element, {});
grid.onRefreshing = function(e) {
refreshingEventArgs = e;
equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh");
};
grid.onRefreshed = function(e) {
refreshedEventArgs = e;
equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh");
};
grid.option("data", this.testData);
equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event");
equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event");
equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered");
});
test("grid fields normalization", function() {
var CustomField = function(config) {
$.extend(true, this, config);
};
jsGrid.fields.custom = CustomField;
try {
var $element = $("#jsGrid"),
gridOptions = {
fields: [
new jsGrid.Field({
name: "text1",
title: "title1"
}),
{
name: "text2",
title: "title2"
},
{
name: "text3",
type: "custom"
}
]
},
grid = new Grid($element, gridOptions);
var field1 = grid.fields[0];
ok(field1 instanceof jsGrid.Field);
equal(field1.name, "text1", "name is set for field");
equal(field1.title, "title1", "title field");
var field2 = grid.fields[1];
ok(field2 instanceof jsGrid.Field);
equal(field2.name, "text2", "name is set for field");
equal(field2.title, "title2", "title field");
var field3 = grid.fields[2];
ok(field3 instanceof CustomField);
equal(field3.name, "text3", "name is set for field");
} finally {
delete jsGrid.fields.custom;
}
});
test("'0' itemTemplate should be rendered", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}],
fields: [
new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } })
]
});
equal(grid._bodyGrid.text(), "0", "item template is rendered");
});
test("grid field name used for header if title is not specified", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
fields: [
new jsGrid.Field({ name: "id" })
]
});
equal(grid._headerRow.text(), "id", "name is rendered in header");
});
test("grid fields header and item rendering", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
fields: [
new jsGrid.Field({
name: "text",
title: "title",
css: "cell-class",
headercss: "header-class",
align: "right"
})
]
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
equal(grid._headerRow.text(), "title", "header rendered");
equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached");
equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached");
ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached");
$secondRow = grid._content.find("." + grid.evenRowClass);
equal($secondRow.text(), "test2", "item rendered");
equal($secondRow.find(".cell-class").length, 1, "css class added to cell");
equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell");
});
test("grid field cellRenderer", function() {
var testItem = { text: "test" },
args;
var $grid = $("#jsGrid");
var gridOptions = {
data: [testItem],
fields: [
{
name: "text",
cellRenderer: function(value, item) {
args = {
value: value,
item: item
};
return $("<td>").addClass("custom-class").text(value);
}
}
]
};
var grid = new Grid($grid, gridOptions);
var $customCell = $grid.find(".custom-class");
equal($customCell.length, 1, "custom cell rendered");
equal($customCell.text(), "test");
deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided");
});
test("grid field 'visible' option", function() {
var $grid = $("#jsGrid");
var gridOptions = {
editing: true,
fields: [
{ name: "id", visible: false },
{ name: "test" }
]
};
var grid = new Grid($grid, gridOptions);
equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells");
grid.option("data", this.testData);
grid.editItem(this.testData[2]);
equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell");
equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell");
equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell");
equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell");
equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell");
equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell");
});
module("inserting");
test("inserting rendering", function() {
var $element = $("#jsGrid"),
gridOptions = {
inserting: true,
fields: [
{
name: "test",
align: "right",
insertcss: "insert-class",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached");
equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered");
equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field");
});
test("field without inserting", function() {
var $element = $("#jsGrid"),
jsGridFieldConfig = {
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
},
gridOptions = {
inserting: true,
fields: [
$.extend({}, jsGridFieldConfig, {
name: "field1",
inserting: false
}),
$.extend({}, jsGridFieldConfig, {
name: "field2"
})
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test1");
grid.fields[1].insertControl.val("test2");
deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item");
});
test("insert data with default location", function() {
var $element = $("#jsGrid"),
inserted = false,
insertingArgs,
insertedArgs,
gridOptions = {
inserting: true,
data: [{field: "default"}],
fields: [
{
name: "field",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
}
],
onItemInserting: function(e) {
insertingArgs = $.extend(true, {}, e);
},
onItemInserted: function(e) {
insertedArgs = $.extend(true, {}, e);
},
controller: {
insertItem: function() {
inserted = true;
}
}
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(insertingArgs.item.field, "test", "field is provided in inserting args");
equal(grid.option("data").length, 2, "data is inserted");
ok(inserted, "controller insertItem was called");
deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted");
equal(insertedArgs.item.field, "test", "field is provided in inserted args");
});
test("insert data with specified insert location", function() {
var $element = $("#jsGrid"),
inserted = false,
insertingArgs,
insertedArgs,
gridOptions = {
inserting: true,
insertRowLocation: "top",
data: [{field: "default"}],
fields: [
{
name: "field",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
}
],
onItemInserting: function(e) {
insertingArgs = $.extend(true, {}, e);
},
onItemInserted: function(e) {
insertedArgs = $.extend(true, {}, e);
},
controller: {
insertItem: function() {
inserted = true;
}
}
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(insertingArgs.item.field, "test", "field is provided in inserting args");
equal(grid.option("data").length, 2, "data is inserted");
ok(inserted, "controller insertItem was called");
deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning");
equal(insertedArgs.item.field, "test", "field is provided in inserted args");
});
test("insertItem accepts item to insert", function() {
var $element = $("#jsGrid"),
itemToInsert = { field: "test" },
insertedItem,
gridOptions = {
data: [],
fields: [
{
name: "field"
}
],
controller: {
insertItem: function(item) {
insertedItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.insertItem(itemToInsert);
deepEqual(grid.option("data")[0], itemToInsert, "data is inserted");
deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item");
});
module("editing");
test("editing rendering", function() {
var $element = $("#jsGrid"),
$editRow,
data = [{
test: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "test",
align: "right",
editcss: "edit-class",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering");
grid.editItem(data[0]);
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
equal($editRow.find(".edit-class").length, 1, "editcss class is attached");
equal($editRow.find(".edit-input").length, 1, "edit control rendered");
equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field");
equal(grid.fields[0].editControl.val(), "value", "edit control value");
});
test("editItem accepts row to edit", function() {
var $element = $("#jsGrid"),
$editRow,
data = [
{ test: "value" }
],
gridOptions = {
editing: true,
fields: [
{ name: "test" }
]
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
grid.cancelEdit();
grid.editItem($row.get(0));
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
});
test("edit item", function() {
var $element = $("#jsGrid"),
editingArgs,
editingRow,
updated = false,
updatingArgs,
updatingRow,
updatedRow,
updatedArgs,
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateItem: function(updatingItem) {
updated = true;
}
},
onItemEditing: function(e) {
editingArgs = $.extend(true, {}, e);
editingRow = grid.rowByItem(data[0])[0];
},
onItemUpdating: function(e) {
updatingArgs = $.extend(true, {}, e);
updatingRow = grid.rowByItem(data[0])[0];
},
onItemUpdated: function(e) {
updatedArgs = $.extend(true, {}, e);
updatedRow = grid.rowByItem(data[0])[0];
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args");
equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args");
equal(editingArgs.row[0], editingRow, "row element is provided in editing event args");
grid.fields[0].editControl.val("new value");
grid.updateItem();
deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args");
deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args");
equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args");
ok(updated, "controller updateItem called");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered");
deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args");
deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args");
equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args");
equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args");
});
test("failed update should not change original item", function() {
var $element = $("#jsGrid"),
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateItem: function(updatingItem) {
return $.Deferred().reject();
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ...");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
updated = false,
cancellingArgs,
cancellingRow,
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateData: function(updatingItem) {
updated = true;
}
},
onItemEditCancelling: function(e) {
cancellingArgs = $.extend(true, {}, e);
cancellingRow = grid.rowByItem(data[0])[0];
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
grid.fields[0].editControl.val("new value");
grid.cancelEdit();
deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args");
equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args");
equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args");
ok(!updated, "controller updateItem was not called");
deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated");
equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored");
});
test("updateItem accepts item to update and new item", function() {
var $element = $("#jsGrid"),
updatingItem,
data = [{
field: "value"
}],
gridOptions = {
fields: [
{ name: "field" }
],
controller: {
updateItem: function(item) {
return updatingItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.updateItem(data[0], { field: "new value" });
deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
});
test("updateItem accepts single argument - item to update", function() {
var $element = $("#jsGrid"),
updatingItem,
data = [{
field: "value"
}],
gridOptions = {
fields: [
{ name: "field" }
],
controller: {
updateItem: function(item) {
return updatingItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
data[0].field = "new value";
grid.updateItem(data[0]);
deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
});
test("editRowRenderer", function() {
var $element = $("#jsGrid"),
data = [
{ value: "test" }
],
gridOptions = {
data: data,
editing: true,
editRowRenderer: function(item, itemIndex) {
return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value));
},
fields: [
{ name: "value" }
]
},
grid = new Grid($element, gridOptions);
grid.editItem(data[0]);
var $editRow = grid._content.find(".custom-edit-row");
equal($editRow.length, 1, "edit row rendered");
equal($editRow.text(), "0:test", "custom edit row renderer rendered");
});
module("deleting");
test("delete item", function() {
var $element = $("#jsGrid"),
deleted = false,
deletingArgs,
deletedArgs,
data = [{
field: "value"
}],
gridOptions = {
confirmDeleting: false,
fields: [
{ name: "field" }
],
controller: {
deleteItem: function(deletingItem) {
deleted = true;
}
},
onItemDeleting: function(e) {
deletingArgs = $.extend(true, {}, e);
},
onItemDeleted: function(e) {
deletedArgs = $.extend(true, {}, e);
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.deleteItem(data[0]);
deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args");
equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(deletingArgs.row.length, 1, "row element is provided in updating event args");
ok(deleted, "controller deleteItem called");
equal(grid.option("data").length, 0, "data row deleted");
deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args");
equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(deletedArgs.row.length, 1, "row element is provided in updating event args");
});
test("deleteItem accepts row", function() {
var $element = $("#jsGrid"),
deletedItem,
itemToDelete = {
field: "value"
},
data = [itemToDelete],
gridOptions = {
confirmDeleting: false,
fields: [
{ name: "field" }
],
controller: {
deleteItem: function(deletingItem) {
deletedItem = deletingItem;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.deleteItem($row);
deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly");
equal(grid.option("data").length, 0, "data row deleted");
});
module("paging");
test("pager is rendered if necessary", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}, {}],
paging: false,
pageSize: 2
});
ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false");
equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false");
grid.option("paging", true);
ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true");
ok(grid._pagerContainer.html(), "pager is rendered when paging=true");
grid.option("data", [{}, {}]);
ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page");
ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true");
});
test("external pagerContainer", function() {
var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(),
$element = $("#jsGrid");
new Grid($element, {
data: [{}, {}, {}],
pagerContainer: $pagerContainer,
paging: true,
pageSize: 2
});
ok($pagerContainer.is(":visible"), "external pager shown");
ok($pagerContainer.html(), "external pager rendered");
});
test("pager functionality", function() {
var $element = $("#jsGrid"),
pager,
pageChangedArgs,
grid = new Grid($element, {
data: [{}, {}, {}, {}, {}, {}, {}, {}, {}],
onPageChanged: function(args) {
pageChangedArgs = args;
},
paging: true,
pageSize: 2,
pageButtonCount: 3
});
equal(grid._pagesCount(), 5, "correct page count");
equal(grid.option("pageIndex"), 1, "pageIndex is initialized");
equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized");
pager = grid._pagerContainer;
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ...");
equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ...");
equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments");
grid.showNextPages();
equal(grid._firstDisplayingPage, 3, "navigate by pages forward");
grid.showPrevPages();
equal(grid._firstDisplayingPage, 1, "navigate by pages backward");
grid.openPage(5);
equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward");
grid.openPage(2);
equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward");
});
test("pager format", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}, {}, {}, {}, {}],
paging: true,
pageSize: 2,
pageIndex: 2,
pageButtonCount: 1,
pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z",
pagePrevText: "<",
pageNextText: ">",
pageFirstText: "<<",
pageLastText: ">>",
pageNavigatorNextText: "np",
pageNavigatorPrevText: "pp"
});
grid._firstDisplayingPage = 2;
grid._refreshPager();
equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified");
});
test("pagerRenderer", function() {
var $element = $("#jsGrid");
var pagerRendererConfig;
var pageSize = 2;
var items = [{}, {}, {}, {}, {}, {}, {}];
var pageCount = Math.ceil(items.length / pageSize);
var grid = new Grid($element, {
data: items,
paging: true,
pageSize: pageSize,
pagerRenderer: function(pagerConfig) {
pagerRendererConfig = pagerConfig;
}
});
deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount });
grid.openPage(2);
deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount });
});
test("loading by page", function() {
var $element = $("#jsGrid"),
data = [],
itemCount = 20;
for(var i = 1; i <= itemCount; i += 1) {
data.push({
value: i
});
}
var gridOptions = {
pageLoading: true,
paging: true,
pageSize: 7,
fields: [
{ name: "value" }
],
controller: {
loadData: function(filter) {
var startIndex = (filter.pageIndex - 1) * filter.pageSize,
result = data.slice(startIndex, startIndex + filter.pageSize);
return {
data: result,
itemsCount: data.length
};
}
}
};
var grid = new Grid($element, gridOptions);
grid.loadData();
var pager = grid._pagerContainer;
var gridData = grid.option("data");
equal(gridData.length, 7, "loaded one page of data");
equal(gridData[0].value, 1, "loaded right data start value");
equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
grid.openPage(3);
gridData = grid.option("data");
equal(gridData.length, 6, "loaded last page of data");
equal(gridData[0].value, 15, "loaded right data start value");
equal(gridData[gridData.length - 1].value, 20, "loaded right data end value");
ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
});
test("'openPage' method ignores indexes out of range", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}],
paging: true,
pageSize: 1
});
grid.openPage(0);
equal(grid.option("pageIndex"), 1, "too small index is ignored");
grid.openPage(3);
equal(grid.option("pageIndex"), 1, "too big index is ignored");
});
module("sorting");
test("sorting", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortOrder, "asc", "asc sorting order for first click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 1);
equal(gridData[1].value, 2);
equal(gridData[2].value, 3);
ok($th.hasClass(grid.sortableClass));
ok($th.hasClass(grid.sortAscClass));
$th.trigger("click");
equal(grid._sortOrder, "desc", "desc sorting order for second click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
ok(!$th.hasClass(grid.sortAscClass));
ok($th.hasClass(grid.sortDescClass));
});
test("sorting with pageLoading", function() {
var $element = $("#jsGrid"),
loadFilter,
gridOptions = {
sorting: true,
pageLoading: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
controller: {
loadData: function(filter) {
loadFilter = filter;
return {
itemsCount: 0,
data: []
};
}
},
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortOrder, "asc", "asc sorting order for first click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter");
equal(loadFilter.sortField, "value", "sort field is provided in loadFilter");
$th.trigger("click");
equal(grid._sortOrder, "desc", "desc sorting order for second click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter");
equal(loadFilter.sortField, "value", "sort field is provided in loadFilter");
});
test("no sorting for column with sorting = false", function() {
var $element = $("#jsGrid");
var gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorting: false }
]
};
var grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortField, null, "sort field is not set for the field with sorting=false");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false");
equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false");
});
test("sort accepts sorting config", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
grid.sort({ field: "value", order: "asc" });
equal(grid._sortOrder, "asc", "asc sorting order is set");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 1);
equal(gridData[1].value, 2);
equal(gridData[2].value, 3);
grid.sort({ field: 0 });
equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
grid.sort("value", "asc");
equal(grid._sortOrder, "asc", "asc sorting order is set");
equal(grid._sortField, grid.fields[0], "sort field is set");
grid.sort(0);
equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting");
equal(grid._sortField, grid.fields[0], "sort field is set");
});
test("getSorting returns current sorting", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting");
grid.sort("value");
deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned");
});
test("sorting css attached correctly when a field is hidden", function() {
var $element = $("#jsGrid");
var gridOptions = {
sorting: true,
data: [],
fields: [
{ name: "field1", visible: false },
{ name: "field2" }
]
};
var grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field");
});
module("canceling events");
test("cancel item edit", function() {
var $element = $("#jsGrid");
var data = [{}];
var gridOptions = {
editing: true,
onItemEditing: function(e) {
e.cancel = true;
},
controller: {
loadData: function() {
return data;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.loadData();
grid.editItem(data[0]);
strictEqual(grid._editingRow, null, "no editing row");
});
test("cancel controller.loadData", function() {
var $element = $("#jsGrid");
var gridOptions = {
onDataLoading: function(e) {
e.cancel = true;
},
controller: {
loadData: function() {
return [{}];
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.loadData();
equal(grid.option("data").length, 0, "no data loaded");
});
test("cancel controller.insertItem", function() {
var $element = $("#jsGrid");
var insertedItem = null;
var gridOptions = {
onItemInserting: function(e) {
e.cancel = true;
},
controller: {
insertItem: function(item) {
insertedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem({ test: "value" });
strictEqual(insertedItem, null, "item was not inserted");
});
test("cancel controller.updateItem", function() {
var $element = $("#jsGrid");
var updatedItem = null;
var existingItem = { test: "value" };
var gridOptions = {
data: [
existingItem
],
onItemUpdating: function(e) {
e.cancel = true;
},
controller: {
updateItem: function(item) {
updatedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.updateItem(existingItem, { test: "new_value" });
strictEqual(updatedItem, null, "item was not updated");
});
test("cancel controller.deleteItem", function() {
var $element = $("#jsGrid");
var deletingItem = { test: "value" };
var deletedItem = null;
var gridOptions = {
data: [
deletingItem
],
confirmDeleting: false,
onItemDeleting: function(e) {
e.cancel = true;
},
controller: {
deleteItem: function(item) {
deletedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.deleteItem(deletingItem);
strictEqual(deletedItem, null, "item was not deleted");
});
module("complex properties binding");
test("rendering", function() {
var $element = $("#jsGrid");
var gridOptions = {
loadMessage: "",
data: [
{ complexProp: { prop: "test" } }
],
fields: [
{ name: "complexProp.prop", title: "" }
]
};
new Grid($element, gridOptions);
equal($element.text(), "test", "complex property value rendered");
});
test("editing", function() {
var $element = $("#jsGrid");
var gridOptions = {
editing: true,
data: [
{ complexProp: { prop: "test" } }
],
fields: [
{ type: "text", name: "complexProp.prop" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor");
});
test("should not fail if property is absent", function() {
var $element = $("#jsGrid");
var gridOptions = {
loadMessage: "",
data: [
{ complexProp: { } }
],
fields: [
{ name: "complexProp.subprop.prop", title: "" }
]
};
new Grid($element, gridOptions);
equal($element.text(), "", "rendered empty value");
});
test("inserting", function() {
var $element = $("#jsGrid");
var insertingItem;
var gridOptions = {
inserting: true,
fields: [
{ type: "text", name: "complexProp.prop" }
],
onItemInserting: function(args) {
insertingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties");
});
test("filtering", function() {
var $element = $("#jsGrid");
var loadFilter;
var gridOptions = {
filtering: true,
fields: [
{ type: "text", name: "complexProp.prop" }
],
controller: {
loadData: function(filter) {
loadFilter = filter;
}
}
};
var grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test");
grid.search();
deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties");
});
test("updating", function() {
var $element = $("#jsGrid");
var updatingItem;
var gridOptions = {
editing: true,
data: [
{ complexProp: { } }
],
fields: [
{ type: "text", name: "complexProp.prop" }
],
onItemUpdating: function(args) {
updatingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test");
grid.updateItem();
deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties");
});
test("update nested prop", function() {
var $element = $("#jsGrid");
var updatingItem;
var previousItem;
var gridOptions = {
editing: true,
data: [
{ prop: { subprop1: "test1", subprop2: "test2" } }
],
fields: [
{ type: "text", name: "prop.subprop1" },
{ type: "text", name: "prop.subprop2" }
],
onItemUpdating: function(args) {
updatingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("new_test1");
grid.updateItem();
var expectedUpdatingItem = {
prop: {
subprop1: "new_test1",
subprop2: "test2"
}
};
deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties");
});
test("updating deeply nested prop", function() {
var $element = $("#jsGrid");
var updatingItem;
var previousItem;
var gridOptions = {
editing: true,
data: [
{ complexProp: { subprop1: { another_prop: "test" } } }
],
fields: [
{ type: "text", name: "complexProp.subprop1.prop1" },
{ type: "text", name: "complexProp.subprop1.subprop2.prop12" }
],
onItemUpdating: function(args) {
updatingItem = $.extend(true, {}, args.item);
previousItem = $.extend(true, {}, args.previousItem);
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test1");
grid.fields[1].editControl.val("test2");
grid.updateItem();
var expectedUpdatingItem = {
complexProp: {
subprop1: {
another_prop: "test",
prop1: "test1",
subprop2: { prop12: "test2" }
}
}
};
var expectedPreviousItem = {
complexProp: {
subprop1: {
another_prop: "test"
}
}
};
deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties");
deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly");
});
module("validation");
test("insertItem should call validation.validate", function() {
var $element = $("#jsGrid");
var fieldValidationRules = { test: "value" };
var validatingArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function(args) {
validatingArgs = args;
return [];
}
},
fields: [
{ type: "text", name: "Name", validate: fieldValidationRules }
]
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1,
row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided");
});
test("insertItem rejected when data is not valid", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem().done(function() {
ok(false, "insertItem should not be completed");
}).fail(function() {
ok(true, "insertItem should fail");
});
});
test("invalidClass is attached on invalid cell on inserting", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Id", visible: false },
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
var $insertCell = grid._insertRow.children().eq(0);
grid.insertItem();
ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached");
equal($insertCell.attr("title"), "Error", "cell tooltip contains error message");
});
test("onItemInvalid callback", function() {
var $element = $("#jsGrid");
var errors = ["Error"];
var onItemInvalidCalled = 0;
var onItemInvalidArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
onItemInvalid: function(args) {
onItemInvalidCalled++;
onItemInvalidArgs = args;
},
validation: {
validate: function(args) {
return !args.value ? errors : [];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem();
equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid");
deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }],
item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided");
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid");
});
test("invalidNotify", function() {
var $element = $("#jsGrid");
var errors = ["Error"];
var invalidNotifyCalled = 0;
var invalidNotifyArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: function(args) {
invalidNotifyCalled++;
invalidNotifyArgs = args;
},
validation: {
validate: function(args) {
return !args.value ? errors : [];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem();
equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid");
deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }],
row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided");
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid");
});
test("invalidMessage", function() {
var $element = $("#jsGrid");
var invalidMessage;
var originalAlert = window.alert;
window.alert = function(message) {
invalidMessage = message;
};
try {
Grid.prototype.invalidMessage = "InvalidTest";
Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] });
var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n");
equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages");
} finally {
window.alert = originalAlert;
}
});
test("updateItem should call validation.validate", function() {
var $element = $("#jsGrid");
var validatingArgs;
var gridOptions = {
data: [{ Name: "" }],
editing: true,
invalidNotify: $.noop,
validation: {
validate: function(args) {
validatingArgs = args;
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: "required" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test");
grid.updateItem();
deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0,
row: grid._getEditRow(), rules: "required" }, "validating args is provided");
});
test("invalidClass is attached on invalid cell on updating", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [{}],
editing: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
var $editCell = grid._getEditRow().children().eq(0);
grid.updateItem();
ok($editCell.hasClass(grid.invalidClass), "invalid class is attached");
equal($editCell.attr("title"), "Error", "cell tooltip contains error message");
});
test("validation should ignore not editable fields", function() {
var invalidNotifyCalled = 0;
var $element = $("#jsGrid");
var validatingArgs;
var gridOptions = {
data: [{ Name: "" }],
editing: true,
invalidNotify: function() {
invalidNotifyCalled++;
},
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", editing: false, validate: "required" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.updateItem();
equal(invalidNotifyCalled, 0, "data is valid");
});
module("api");
test("reset method should go the first page when pageLoading is truned on", function() {
var items = [{ Name: "1" }, { Name: "2" }];
var $element = $("#jsGrid");
var gridOptions = {
paging: true,
pageSize: 1,
pageLoading: true,
autoload: true,
controller: {
loadData: function(args) {
return {
data: [items[args.pageIndex - 1]],
itemsCount: items.length
};
}
},
fields: [
{ type: "text", name: "Name" }
]
};
var grid = new Grid($element, gridOptions);
grid.openPage(2);
grid.reset();
equal(grid._bodyGrid.text(), "1", "grid content reset");
});
module("i18n");
test("set locale by name", function() {
jsGrid.locales.my_lang = {
grid: {
test: "test_text"
}
};
jsGrid.locale("my_lang");
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "test"), "test_text", "option localized");
});
test("set locale by config", function() {
jsGrid.locale( {
grid: {
test: "test_text"
}
});
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "test"), "test_text", "option localized");
});
test("locale throws exception for unknown locale", function() {
throws(function() {
jsGrid.locale("unknown_lang");
}, /unknown_lang/, "locale threw an exception");
});
module("controller promise");
asyncTest("should support jQuery promise success callback", 1, function() {
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
var d = $.Deferred();
setTimeout(function() {
d.resolve(data);
start();
});
return d.promise();
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
asyncTest("should support jQuery promise fail callback", 1, function() {
var failArgs = {};
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
var d = $.Deferred();
setTimeout(function() {
d.reject(failArgs);
start();
});
return d.promise();
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.fail(function(result) {
equal(result, failArgs, "fail args provided to fail callback");
});
});
asyncTest("should support JS promise success callback", 1, function() {
if(typeof Promise === "undefined") {
ok(true, "Promise not supported");
start();
return;
}
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(data);
start();
});
});
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
asyncTest("should support JS promise fail callback", 1, function() {
if(typeof Promise === "undefined") {
ok(true, "Promise not supported");
start();
return;
}
var failArgs = {};
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(failArgs);
start();
});
});
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.fail(function(result) {
equal(result, failArgs, "fail args provided to fail callback");
});
});
test("should support non-promise result", 1, function() {
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return data;
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
module("renderTemplate");
test("should pass undefined and null arguments to the renderer", function() {
var rendererArgs;
var rendererContext;
var context = {};
var renderer = function() {
rendererArgs = arguments;
rendererContext = this;
};
Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" });
equal(rendererArgs.length, 3);
strictEqual(rendererArgs[0], undefined, "undefined passed");
strictEqual(rendererArgs[1], null, "null passed");
strictEqual(rendererArgs[2], "test", "null passed");
strictEqual(rendererContext, context, "context is preserved");
});
module("Data Export", {
setup: function() {
this.exportConfig = {};
this.exportConfig.type = "csv";
this.exportConfig.subset = "all";
this.exportConfig.delimiter = "|";
this.exportConfig.includeHeaders = true;
this.exportConfig.encapsulate = true;
this.element = $("#jsGrid");
this.gridOptions = {
width: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
pageSize: 2,
data: [
{ "Name": "Otto Clay", "Country": 1, "Married": false },
{ "Name": "Connor Johnston", "Country": 2, "Married": true },
{ "Name": "Lacey Hess", "Country": 2, "Married": false },
{ "Name": "Timothy Henson", "Country": 1, "Married": true }
],
fields: [
{ name: "Name", type: "text", width: 150, validate: "required" },
{ name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{ type: "control" }
]
}
}
});
/* Base Choice Criteria
type: csv
subset: all
delimiter: |
includeHeaders: true
encapsulate: true
*/
test("Should export data: Base Choice",function(){
var grid = new Grid($(this.element), this.gridOptions);
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source");
});
test("Should export data: defaults = BCC",function(){
var grid = new Grid($(this.element), this.gridOptions);
var data = grid.exportData();
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice");
});
test("Should export data: subset=visible", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.subset = "visible";
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
//expected += '"Lacey Hess"|"Canada"|"false"\r\n';
//expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV of visible records");
});
test("Should export data: delimiter=;", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.delimiter = ";";
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name";"Country";"Is Married"\r\n';
expected += '"Otto Clay";"United States";"false"\r\n';
expected += '"Connor Johnston";"Canada";"true"\r\n';
expected += '"Lacey Hess";"Canada";"false"\r\n';
expected += '"Timothy Henson";"United States";"true"\r\n';
equal(data, expected, "Output CSV with non-default delimiter");
});
test("Should export data: headers=false", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.includeHeaders = false;
var data = grid.exportData(this.exportConfig);
var expected = "";
//expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV without Headers");
});
test("Should export data: encapsulate=false", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.encapsulate = false;
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += 'Name|Country|Is Married\r\n';
expected += 'Otto Clay|United States|false\r\n';
expected += 'Connor Johnston|Canada|true\r\n';
expected += 'Lacey Hess|Canada|false\r\n';
expected += 'Timothy Henson|United States|true\r\n';
equal(data, expected, "Output CSV without encapsulation");
});
test("Should export filtered data", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig['filter'] = function(item){
if (item["Name"].indexOf("O") === 0)
return true
};
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
//expected += '"Connor Johnston"|"Canada"|"true"\r\n';
//expected += '"Lacey Hess"|"Canada"|"false"\r\n';
//expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV filtered to show names starting with O");
});
test("Should export data: transformed value", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig['transforms'] = {};
this.exportConfig.transforms['Married'] = function(value){
if (value === true) return "Yes"
if (value === false) return "No"
};
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"No"\r\n';
expected += '"Connor Johnston"|"Canada"|"Yes"\r\n';
expected += '"Lacey Hess"|"Canada"|"No"\r\n';
expected += '"Timothy Henson"|"United States"|"Yes"\r\n';
equal(data, expected, "Output CSV column value transformed properly");
});
});
<MSG> Core: Hide unavalable pager nav buttons
<DFF> @@ -1371,7 +1371,8 @@ $(function() {
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
- equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ...");
+ equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ...");
+ equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
| 2 | Core: Hide unavalable pager nav buttons | 1 | .js | tests | mit | tabalinas/jsgrid |
10069259 | <NME> jsgrid.tests.js
<BEF> $(function() {
var Grid = jsGrid.Grid,
JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID;
Grid.prototype.updateOnResize = false;
module("basic");
test("default creation", function() {
var gridOptions = {
simpleOption: "test",
complexOption: {
a: "subtest",
b: 1,
c: {}
}
},
grid = new Grid("#jsGrid", gridOptions);
equal(grid._container[0], $("#jsGrid")[0], "container saved");
equal(grid.simpleOption, "test", "primitive option extended");
equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended");
});
test("jquery adapter creation", function() {
var gridOptions = {
option: "test"
},
$element = $("#jsGrid"),
result = $element.jsGrid(gridOptions),
grid = $element.data(JSGRID_DATA_KEY);
equal(result, $element, "jquery fn returned source jQueryElement");
ok(grid instanceof Grid, "jsGrid saved to jquery data");
equal(grid.option, "test", "options provided");
});
test("destroy", function() {
var $element = $("#jsGrid"),
grid;
$element.jsGrid({});
grid = $element.data(JSGRID_DATA_KEY);
grid.destroy();
strictEqual($element.html(), "", "content is removed");
strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed");
});
test("jquery adapter second call changes option value", function() {
var $element = $("#jsGrid"),
gridOptions = {
option: "test"
},
grid;
$element.jsGrid(gridOptions);
grid = $element.data(JSGRID_DATA_KEY);
gridOptions.option = "new test";
$element.jsGrid(gridOptions);
equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed");
equal(grid.option, "new test", "option changed");
});
test("jquery adapter invokes jsGrid method", function() {
var methodResult = "",
$element = $("#jsGrid"),
gridOptions = {
method: function(str) {
methodResult = "test_" + str;
}
};
$element.jsGrid(gridOptions);
$element.jsGrid("method", "invoke");
equal(methodResult, "test_invoke", "method invoked");
});
test("onInit callback", function() {
var $element = $("#jsGrid"),
onInitArguments,
gridOptions = {
onInit: function(args) {
onInitArguments = args;
}
};
var grid = new Grid($element, gridOptions);
equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments");
});
test("controller methods are $.noop when not specified", function() {
var $element = $("#jsGrid"),
gridOptions = {
controller: {}
},
testOption;
$element.jsGrid(gridOptions);
deepEqual($element.data(JSGRID_DATA_KEY)._controller, {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
}, "controller has stub methods");
});
test("option method", function() {
var $element = $("#jsGrid"),
gridOptions = {
test: "value"
},
testOption;
$element.jsGrid(gridOptions);
testOption = $element.jsGrid("option", "test");
equal(testOption, "value", "read option value");
$element.jsGrid("option", "test", "new_value");
testOption = $element.jsGrid("option", "test");
equal(testOption, "new_value", "set option value");
});
test("fieldOption method", function() {
var dataLoadedCount = 0;
var $element = $("#jsGrid"),
gridOptions = {
loadMessage: "",
autoload: true,
controller: {
loadData: function() {
dataLoadedCount++;
return [{ prop1: "value1", prop2: "value2", prop3: "value3" }];
}
},
fields: [
{ name: "prop1", title: "_" }
]
};
$element.jsGrid(gridOptions);
var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name");
equal(fieldOptionValue, "prop1", "read field option");
$element.jsGrid("fieldOption", "prop1", "name", "prop2");
equal($element.text(), "_value2", "set field option by field name");
equal(dataLoadedCount, 1, "data not reloaded on field option change");
$element.jsGrid("fieldOption", 0, "name", "prop3");
equal($element.text(), "_value3", "set field option by field index");
});
test("option changing event handlers", function() {
var $element = $("#jsGrid"),
optionChangingEventArgs,
optionChangedEventArgs,
gridOptions = {
test: "testValue",
another: "anotherValue",
onOptionChanging: function(e) {
optionChangingEventArgs = $.extend({}, e);
e.option = "another";
e.newValue = e.newValue + "_" + this.another;
},
onOptionChanged: function(e) {
optionChangedEventArgs = $.extend({}, e);
}
},
anotherOption;
$element.jsGrid(gridOptions);
$element.jsGrid("option", "test", "newTestValue");
equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging");
equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging");
equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging");
anotherOption = $element.jsGrid("option", "another");
equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value");
equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged");
equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged");
});
test("common layout rendering", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {}),
$headerGrid,
$headerGridTable,
$bodyGrid,
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header");
ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body");
ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container");
$headerGrid = $element.children().eq(0);
$headerGridTable = $headerGrid.children().first();
ok($headerGridTable.hasClass(grid.tableClass), "header table");
equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row");
equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row");
equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row");
ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class");
ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class");
ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class");
$bodyGrid = $element.children().eq(1);
$bodyGridTable = $bodyGrid.children().first();
ok($bodyGridTable.hasClass(grid.tableClass), "body table");
equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table");
equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row");
equal($bodyGridTable.text(), grid.noDataContent, "no data text");
});
test("set default options with setDefaults", function() {
jsGrid.setDefaults({
defaultOption: "test"
});
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "defaultOption"), "test", "default option set");
});
module("loading");
test("loading with controller", function() {
var $element = $("#jsGrid"),
data = [
{ test: "test1" },
{ test: "test2" }
],
gridOptions = {
controller: {
loadData: function() {
return data;
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(grid.option("data"), data, "loadData loads data");
});
test("loadData throws exception when controller method not found", function() {
var $element = $("#jsGrid");
var grid = new Grid($element);
grid._controller = {};
throws(function() {
grid.loadData();
}, /loadData/, "loadData threw an exception");
});
test("onError event should be fired on controller fail", function() {
var errorArgs,
errorFired = 0,
$element = $("#jsGrid"),
gridOptions = {
controller: {
loadData: function() {
return $.Deferred().reject({ value: 1 }, "test").promise();
}
},
onError: function(args) {
errorFired++;
errorArgs = args;
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(errorFired, 1, "onError handler fired");
deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params");
});
asyncTest("autoload should call loadData after render", 1, function() {
new Grid($("#jsGrid"), {
autoload: true,
controller: {
loadData: function() {
ok(true, "autoload calls loadData on creation");
start();
return [];
}
}
});
});
test("loading filtered data", function() {
var filteredData,
loadingArgs,
loadedArgs,
$element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
filtering: true,
fields: [
{
name: "field",
filterValue: function(value) {
return "test";
}
}
],
onDataLoading: function(e) {
loadingArgs = $.extend(true, {}, e);
},
onDataLoaded: function(e) {
loadedArgs = $.extend(true, {}, e);
},
controller: {
loadData: function(filter) {
filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
equal(loadingArgs.filter.field, "test");
equal(grid.option("data").length, 2, "filtered data loaded");
deepEqual(loadedArgs.data, filteredData);
});
asyncTest("loading indication", function() {
var timeout = 10,
stage = "initial",
$element = $("#jsGrid"),
gridOptions = {
loadIndication: true,
loadIndicationDelay: timeout,
loadMessage: "loading...",
loadIndicator: function(config) {
equal(config.message, gridOptions.loadMessage, "message provided");
ok(config.container.jquery, "grid container is provided");
return {
show: function() {
stage = "started";
},
hide: function() {
stage = "finished";
}
};
},
fields: [
{ name: "field" }
],
controller: {
loadData: function() {
var deferred = $.Deferred();
equal(stage, "initial", "initial stage");
setTimeout(function() {
equal(stage, "started", "loading started");
deferred.resolve([]);
equal(stage, "finished", "loading finished");
start();
}, timeout);
return deferred.promise();
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
});
asyncTest("loadingIndication=false should not show loading", 0, function() {
var $element = $("#jsGrid"),
timeout = 10,
gridOptions = {
loadIndication: false,
loadIndicationDelay: timeout,
loadIndicator: function() {
return {
show: function() {
ok(false, "should not call show");
},
hide: function() {
ok(false, "should not call hide");
}
};
},
fields: [
{ name: "field" }
],
controller: {
loadData: function() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve([]);
start();
}, timeout);
return deferred.promise();
}
}
},
grid = new Grid($element, gridOptions);
grid.loadData();
});
test("search", function() {
var $element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
pageIndex: 2,
_sortField: "field",
_sortOrder: "desc",
filtering: true,
fields: [
{
name: "field",
filterValue: function(value) {
return "test";
}
}
],
controller: {
loadData: function(filter) {
var filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.search();
equal(grid.option("data").length, 2, "data filtered");
strictEqual(grid.option("pageIndex"), 1, "pageIndex reset");
strictEqual(grid._sortField, null, "sortField reset");
strictEqual(grid._sortOrder, "asc", "sortOrder reset");
});
test("change loadStrategy on the fly", function() {
var $element = $("#jsGrid");
var gridOptions = {
controller: {
loadData: function() {
return [];
}
}
};
var grid = new Grid($element, gridOptions);
grid.option("loadStrategy", {
firstDisplayIndex: function() {
return 0;
},
lastDisplayIndex: function() {
return 1;
},
loadParams: function() {
return [];
},
finishLoad: function() {
grid.option("data", [{}]);
}
});
grid.loadData();
equal(grid.option("data").length, 1, "new load strategy is applied");
});
module("filtering");
test("filter rendering", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
fields: [
{
name: "test",
align: "right",
filtercss: "filter-class",
filterTemplate: function() {
var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached");
equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered");
equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field");
});
test("filter get/clear", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
controller: {
loadData: function() {
return [];
}
},
fields: [
{
name: "field",
filterTemplate: function() {
return this.filterControl = $("<input>").attr("type", "text");
},
filterValue: function() {
return this.filterControl.val();
}
}
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test");
deepEqual(grid.getFilter(), { field: "test" }, "get filter");
grid.clearFilter();
deepEqual(grid.getFilter(), { field: "" }, "filter cleared");
equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared");
});
test("field without filtering", function() {
var $element = $("#jsGrid"),
jsGridFieldConfig = {
filterTemplate: function() {
var result = this.filterControl = $("<input>").attr("type", "text");
return result;
},
filterValue: function(value) {
if(!arguments.length) {
return this.filterControl.val();
}
this.filterControl.val(value);
}
},
gridOptions = {
filtering: true,
fields: [
$.extend({}, jsGridFieldConfig, {
name: "field1",
filtering: false
}),
$.extend({}, jsGridFieldConfig, {
name: "field2"
})
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test1");
grid.fields[1].filterControl.val("test2");
deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter");
});
test("search with filter", function() {
var $element = $("#jsGrid"),
data = [
{ field: "test" },
{ field: "test_another" },
{ field: "test_another" },
{ field: "test" }
],
gridOptions = {
fields: [
{
name: "field"
}
],
controller: {
loadData: function(filter) {
var filteredData = $.grep(data, function(item) {
return item.field === filter.field;
});
return filteredData;
}
}
},
grid = new Grid($element, gridOptions);
grid.search({ field: "test" });
equal(grid.option("data").length, 2, "data filtered");
});
test("filtering with static data should not do actual filtering", function() {
var $element = $("#jsGrid"),
gridOptions = {
filtering: true,
fields: [
{ type: "text", name: "field" }
],
data: [
{ name: "value1" },
{ name: "value2" }
]
},
grid = new Grid($element, gridOptions);
grid._filterRow.find("input").val("1");
grid.search();
equal(grid.option("data").length, 2, "data is not filtered");
});
module("nodatarow");
test("nodatarow after bind on empty array", function() {
var $element = $("#jsGrid"),
gridOptions = {},
grid = new Grid($element, gridOptions);
grid.option("data", []);
equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered");
equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached");
equal(grid._content.text(), grid.noDataContent, "no data text rendered");
});
test("nodatarow customize content", function() {
var noDataMessage = "NoData Custom Content",
$element = $("#jsGrid"),
gridOptions = {
noDataContent: function() {
return noDataMessage;
}
},
grid = new Grid($element, gridOptions);
grid.option("data", []);
equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached");
equal(grid._content.text(), noDataMessage, "custom noDataContent");
});
module("row rendering", {
setup: function() {
this.testData = [
{ id: 1, text: "test1" },
{ id: 2, text: "test2" },
{ id: 3, text: "test3" }
];
}
});
test("rows rendered correctly", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData
},
grid = new Grid($element, gridOptions);
equal(grid._content.children().length, 3, "rows rendered");
equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items");
equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items");
});
test("custom rowClass", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData,
rowClass: "custom-row-cls"
},
grid = new Grid($element, gridOptions);
equal(grid._content.find("." + grid.oddRowClass).length, 2);
equal(grid._content.find("." + grid.evenRowClass).length, 1);
equal(grid._content.find(".custom-row-cls").length, 3, "custom row class");
});
test("custom rowClass callback", function() {
var $element = $("#jsGrid"),
gridOptions = {
data: this.testData,
rowClass: function(item, index) {
return item.text;
}
},
grid = new Grid($element, gridOptions);
equal(grid._content.find("." + grid.oddRowClass).length, 2);
equal(grid._content.find("." + grid.evenRowClass).length, 1);
equal(grid._content.find(".test1").length, 1, "custom row class");
equal(grid._content.find(".test2").length, 1, "custom row class");
equal(grid._content.find(".test3").length, 1, "custom row class");
});
test("rowClick standard handler", function() {
var $element = $("#jsGrid"),
$secondRow,
grid = new Grid($element, { editing: true });
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("click", $.Event($secondRow));
equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow");
});
test("rowClick handler", function() {
var rowClickArgs,
$element = $("#jsGrid"),
$secondRow,
gridOptions = {
rowClick: function(args) {
rowClickArgs = args;
}
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("click", $.Event($secondRow));
ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg");
equal(rowClickArgs.item, this.testData[1], "item arg");
equal(rowClickArgs.itemIndex, 1, "itemIndex arg");
});
test("row selecting with selectedRowClass", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
selecting: true
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("mouseenter", $.Event($secondRow));
ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass");
$secondRow.trigger("mouseleave", $.Event($secondRow));
ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass");
});
test("no row selecting while selection is disabled", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
selecting: false
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
$secondRow = grid._content.find("." + grid.evenRowClass);
$secondRow.trigger("mouseenter", $.Event($secondRow));
ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass");
});
test("refreshing and refreshed callbacks", function() {
var refreshingEventArgs,
refreshedEventArgs,
$element = $("#jsGrid"),
grid = new Grid($element, {});
grid.onRefreshing = function(e) {
refreshingEventArgs = e;
equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh");
};
grid.onRefreshed = function(e) {
refreshedEventArgs = e;
equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh");
};
grid.option("data", this.testData);
equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event");
equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event");
equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered");
});
test("grid fields normalization", function() {
var CustomField = function(config) {
$.extend(true, this, config);
};
jsGrid.fields.custom = CustomField;
try {
var $element = $("#jsGrid"),
gridOptions = {
fields: [
new jsGrid.Field({
name: "text1",
title: "title1"
}),
{
name: "text2",
title: "title2"
},
{
name: "text3",
type: "custom"
}
]
},
grid = new Grid($element, gridOptions);
var field1 = grid.fields[0];
ok(field1 instanceof jsGrid.Field);
equal(field1.name, "text1", "name is set for field");
equal(field1.title, "title1", "title field");
var field2 = grid.fields[1];
ok(field2 instanceof jsGrid.Field);
equal(field2.name, "text2", "name is set for field");
equal(field2.title, "title2", "title field");
var field3 = grid.fields[2];
ok(field3 instanceof CustomField);
equal(field3.name, "text3", "name is set for field");
} finally {
delete jsGrid.fields.custom;
}
});
test("'0' itemTemplate should be rendered", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}],
fields: [
new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } })
]
});
equal(grid._bodyGrid.text(), "0", "item template is rendered");
});
test("grid field name used for header if title is not specified", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
fields: [
new jsGrid.Field({ name: "id" })
]
});
equal(grid._headerRow.text(), "id", "name is rendered in header");
});
test("grid fields header and item rendering", function() {
var $element = $("#jsGrid"),
$secondRow,
gridOptions = {
fields: [
new jsGrid.Field({
name: "text",
title: "title",
css: "cell-class",
headercss: "header-class",
align: "right"
})
]
},
grid = new Grid($element, gridOptions);
grid.option("data", this.testData);
equal(grid._headerRow.text(), "title", "header rendered");
equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached");
equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached");
ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached");
$secondRow = grid._content.find("." + grid.evenRowClass);
equal($secondRow.text(), "test2", "item rendered");
equal($secondRow.find(".cell-class").length, 1, "css class added to cell");
equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell");
});
test("grid field cellRenderer", function() {
var testItem = { text: "test" },
args;
var $grid = $("#jsGrid");
var gridOptions = {
data: [testItem],
fields: [
{
name: "text",
cellRenderer: function(value, item) {
args = {
value: value,
item: item
};
return $("<td>").addClass("custom-class").text(value);
}
}
]
};
var grid = new Grid($grid, gridOptions);
var $customCell = $grid.find(".custom-class");
equal($customCell.length, 1, "custom cell rendered");
equal($customCell.text(), "test");
deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided");
});
test("grid field 'visible' option", function() {
var $grid = $("#jsGrid");
var gridOptions = {
editing: true,
fields: [
{ name: "id", visible: false },
{ name: "test" }
]
};
var grid = new Grid($grid, gridOptions);
equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells");
grid.option("data", this.testData);
grid.editItem(this.testData[2]);
equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell");
equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell");
equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell");
equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell");
equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell");
equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell");
});
module("inserting");
test("inserting rendering", function() {
var $element = $("#jsGrid"),
gridOptions = {
inserting: true,
fields: [
{
name: "test",
align: "right",
insertcss: "insert-class",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached");
equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered");
equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field");
});
test("field without inserting", function() {
var $element = $("#jsGrid"),
jsGridFieldConfig = {
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
},
gridOptions = {
inserting: true,
fields: [
$.extend({}, jsGridFieldConfig, {
name: "field1",
inserting: false
}),
$.extend({}, jsGridFieldConfig, {
name: "field2"
})
]
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test1");
grid.fields[1].insertControl.val("test2");
deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item");
});
test("insert data with default location", function() {
var $element = $("#jsGrid"),
inserted = false,
insertingArgs,
insertedArgs,
gridOptions = {
inserting: true,
data: [{field: "default"}],
fields: [
{
name: "field",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
}
],
onItemInserting: function(e) {
insertingArgs = $.extend(true, {}, e);
},
onItemInserted: function(e) {
insertedArgs = $.extend(true, {}, e);
},
controller: {
insertItem: function() {
inserted = true;
}
}
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(insertingArgs.item.field, "test", "field is provided in inserting args");
equal(grid.option("data").length, 2, "data is inserted");
ok(inserted, "controller insertItem was called");
deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted");
equal(insertedArgs.item.field, "test", "field is provided in inserted args");
});
test("insert data with specified insert location", function() {
var $element = $("#jsGrid"),
inserted = false,
insertingArgs,
insertedArgs,
gridOptions = {
inserting: true,
insertRowLocation: "top",
data: [{field: "default"}],
fields: [
{
name: "field",
insertTemplate: function() {
var result = this.insertControl = $("<input>").attr("type", "text");
return result;
},
insertValue: function() {
return this.insertControl.val();
}
}
],
onItemInserting: function(e) {
insertingArgs = $.extend(true, {}, e);
},
onItemInserted: function(e) {
insertedArgs = $.extend(true, {}, e);
},
controller: {
insertItem: function() {
inserted = true;
}
}
},
grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(insertingArgs.item.field, "test", "field is provided in inserting args");
equal(grid.option("data").length, 2, "data is inserted");
ok(inserted, "controller insertItem was called");
deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning");
equal(insertedArgs.item.field, "test", "field is provided in inserted args");
});
test("insertItem accepts item to insert", function() {
var $element = $("#jsGrid"),
itemToInsert = { field: "test" },
insertedItem,
gridOptions = {
data: [],
fields: [
{
name: "field"
}
],
controller: {
insertItem: function(item) {
insertedItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.insertItem(itemToInsert);
deepEqual(grid.option("data")[0], itemToInsert, "data is inserted");
deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item");
});
module("editing");
test("editing rendering", function() {
var $element = $("#jsGrid"),
$editRow,
data = [{
test: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "test",
align: "right",
editcss: "edit-class",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input");
return result;
}
}
]
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering");
grid.editItem(data[0]);
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
equal($editRow.find(".edit-class").length, 1, "editcss class is attached");
equal($editRow.find(".edit-input").length, 1, "edit control rendered");
equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached");
ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached");
ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field");
equal(grid.fields[0].editControl.val(), "value", "edit control value");
});
test("editItem accepts row to edit", function() {
var $element = $("#jsGrid"),
$editRow,
data = [
{ test: "value" }
],
gridOptions = {
editing: true,
fields: [
{ name: "test" }
]
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
grid.cancelEdit();
grid.editItem($row.get(0));
$editRow = grid._content.find("." + grid.editRowClass);
equal($editRow.length, 1, "edit row rendered");
});
test("edit item", function() {
var $element = $("#jsGrid"),
editingArgs,
editingRow,
updated = false,
updatingArgs,
updatingRow,
updatedRow,
updatedArgs,
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateItem: function(updatingItem) {
updated = true;
}
},
onItemEditing: function(e) {
editingArgs = $.extend(true, {}, e);
editingRow = grid.rowByItem(data[0])[0];
},
onItemUpdating: function(e) {
updatingArgs = $.extend(true, {}, e);
updatingRow = grid.rowByItem(data[0])[0];
},
onItemUpdated: function(e) {
updatedArgs = $.extend(true, {}, e);
updatedRow = grid.rowByItem(data[0])[0];
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args");
equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args");
equal(editingArgs.row[0], editingRow, "row element is provided in editing event args");
grid.fields[0].editControl.val("new value");
grid.updateItem();
deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args");
deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args");
equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args");
ok(updated, "controller updateItem called");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered");
deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args");
deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args");
equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args");
equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args");
});
test("failed update should not change original item", function() {
var $element = $("#jsGrid"),
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateItem: function(updatingItem) {
return $.Deferred().reject();
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ...");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
updated = false,
cancellingArgs,
cancellingRow,
data = [{
field: "value"
}],
gridOptions = {
editing: true,
fields: [
{
name: "field",
editTemplate: function(value) {
var result = this.editControl = $("<input>").attr("type", "text").val(value);
return result;
},
editValue: function() {
return this.editControl.val();
}
}
],
controller: {
updateData: function(updatingItem) {
updated = true;
}
},
onItemEditCancelling: function(e) {
cancellingArgs = $.extend(true, {}, e);
cancellingRow = grid.rowByItem(data[0])[0];
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.editItem(data[0]);
grid.fields[0].editControl.val("new value");
grid.cancelEdit();
deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args");
equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args");
equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args");
ok(!updated, "controller updateItem was not called");
deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated");
equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed");
equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored");
});
test("updateItem accepts item to update and new item", function() {
var $element = $("#jsGrid"),
updatingItem,
data = [{
field: "value"
}],
gridOptions = {
fields: [
{ name: "field" }
],
controller: {
updateItem: function(item) {
return updatingItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.updateItem(data[0], { field: "new value" });
deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
});
test("updateItem accepts single argument - item to update", function() {
var $element = $("#jsGrid"),
updatingItem,
data = [{
field: "value"
}],
gridOptions = {
fields: [
{ name: "field" }
],
controller: {
updateItem: function(item) {
return updatingItem = item;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
data[0].field = "new value";
grid.updateItem(data[0]);
deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly");
deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated");
});
test("editRowRenderer", function() {
var $element = $("#jsGrid"),
data = [
{ value: "test" }
],
gridOptions = {
data: data,
editing: true,
editRowRenderer: function(item, itemIndex) {
return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value));
},
fields: [
{ name: "value" }
]
},
grid = new Grid($element, gridOptions);
grid.editItem(data[0]);
var $editRow = grid._content.find(".custom-edit-row");
equal($editRow.length, 1, "edit row rendered");
equal($editRow.text(), "0:test", "custom edit row renderer rendered");
});
module("deleting");
test("delete item", function() {
var $element = $("#jsGrid"),
deleted = false,
deletingArgs,
deletedArgs,
data = [{
field: "value"
}],
gridOptions = {
confirmDeleting: false,
fields: [
{ name: "field" }
],
controller: {
deleteItem: function(deletingItem) {
deleted = true;
}
},
onItemDeleting: function(e) {
deletingArgs = $.extend(true, {}, e);
},
onItemDeleted: function(e) {
deletedArgs = $.extend(true, {}, e);
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
grid.deleteItem(data[0]);
deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args");
equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(deletingArgs.row.length, 1, "row element is provided in updating event args");
ok(deleted, "controller deleteItem called");
equal(grid.option("data").length, 0, "data row deleted");
deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args");
equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args");
equal(deletedArgs.row.length, 1, "row element is provided in updating event args");
});
test("deleteItem accepts row", function() {
var $element = $("#jsGrid"),
deletedItem,
itemToDelete = {
field: "value"
},
data = [itemToDelete],
gridOptions = {
confirmDeleting: false,
fields: [
{ name: "field" }
],
controller: {
deleteItem: function(deletingItem) {
deletedItem = deletingItem;
}
}
},
grid = new Grid($element, gridOptions);
grid.option("data", data);
var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.deleteItem($row);
deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly");
equal(grid.option("data").length, 0, "data row deleted");
});
module("paging");
test("pager is rendered if necessary", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}, {}],
paging: false,
pageSize: 2
});
ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false");
equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false");
grid.option("paging", true);
ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true");
ok(grid._pagerContainer.html(), "pager is rendered when paging=true");
grid.option("data", [{}, {}]);
ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page");
ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true");
});
test("external pagerContainer", function() {
var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(),
$element = $("#jsGrid");
new Grid($element, {
data: [{}, {}, {}],
pagerContainer: $pagerContainer,
paging: true,
pageSize: 2
});
ok($pagerContainer.is(":visible"), "external pager shown");
ok($pagerContainer.html(), "external pager rendered");
});
test("pager functionality", function() {
var $element = $("#jsGrid"),
pager,
pageChangedArgs,
grid = new Grid($element, {
data: [{}, {}, {}, {}, {}, {}, {}, {}, {}],
onPageChanged: function(args) {
pageChangedArgs = args;
},
paging: true,
pageSize: 2,
pageButtonCount: 3
});
equal(grid._pagesCount(), 5, "correct page count");
equal(grid.option("pageIndex"), 1, "pageIndex is initialized");
equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized");
pager = grid._pagerContainer;
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ...");
equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ...");
equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments");
grid.showNextPages();
equal(grid._firstDisplayingPage, 3, "navigate by pages forward");
grid.showPrevPages();
equal(grid._firstDisplayingPage, 1, "navigate by pages backward");
grid.openPage(5);
equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward");
grid.openPage(2);
equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward");
});
test("pager format", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}, {}, {}, {}, {}],
paging: true,
pageSize: 2,
pageIndex: 2,
pageButtonCount: 1,
pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z",
pagePrevText: "<",
pageNextText: ">",
pageFirstText: "<<",
pageLastText: ">>",
pageNavigatorNextText: "np",
pageNavigatorPrevText: "pp"
});
grid._firstDisplayingPage = 2;
grid._refreshPager();
equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified");
});
test("pagerRenderer", function() {
var $element = $("#jsGrid");
var pagerRendererConfig;
var pageSize = 2;
var items = [{}, {}, {}, {}, {}, {}, {}];
var pageCount = Math.ceil(items.length / pageSize);
var grid = new Grid($element, {
data: items,
paging: true,
pageSize: pageSize,
pagerRenderer: function(pagerConfig) {
pagerRendererConfig = pagerConfig;
}
});
deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount });
grid.openPage(2);
deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount });
});
test("loading by page", function() {
var $element = $("#jsGrid"),
data = [],
itemCount = 20;
for(var i = 1; i <= itemCount; i += 1) {
data.push({
value: i
});
}
var gridOptions = {
pageLoading: true,
paging: true,
pageSize: 7,
fields: [
{ name: "value" }
],
controller: {
loadData: function(filter) {
var startIndex = (filter.pageIndex - 1) * filter.pageSize,
result = data.slice(startIndex, startIndex + filter.pageSize);
return {
data: result,
itemsCount: data.length
};
}
}
};
var grid = new Grid($element, gridOptions);
grid.loadData();
var pager = grid._pagerContainer;
var gridData = grid.option("data");
equal(gridData.length, 7, "loaded one page of data");
equal(gridData[0].value, 1, "loaded right data start value");
equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
grid.openPage(3);
gridData = grid.option("data");
equal(gridData.length, 6, "loaded last page of data");
equal(gridData[0].value, 15, "loaded right data start value");
equal(gridData[gridData.length - 1].value, 20, "loaded right data end value");
ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
});
test("'openPage' method ignores indexes out of range", function() {
var $element = $("#jsGrid"),
grid = new Grid($element, {
data: [{}, {}],
paging: true,
pageSize: 1
});
grid.openPage(0);
equal(grid.option("pageIndex"), 1, "too small index is ignored");
grid.openPage(3);
equal(grid.option("pageIndex"), 1, "too big index is ignored");
});
module("sorting");
test("sorting", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortOrder, "asc", "asc sorting order for first click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 1);
equal(gridData[1].value, 2);
equal(gridData[2].value, 3);
ok($th.hasClass(grid.sortableClass));
ok($th.hasClass(grid.sortAscClass));
$th.trigger("click");
equal(grid._sortOrder, "desc", "desc sorting order for second click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
ok(!$th.hasClass(grid.sortAscClass));
ok($th.hasClass(grid.sortDescClass));
});
test("sorting with pageLoading", function() {
var $element = $("#jsGrid"),
loadFilter,
gridOptions = {
sorting: true,
pageLoading: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
controller: {
loadData: function(filter) {
loadFilter = filter;
return {
itemsCount: 0,
data: []
};
}
},
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortOrder, "asc", "asc sorting order for first click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter");
equal(loadFilter.sortField, "value", "sort field is provided in loadFilter");
$th.trigger("click");
equal(grid._sortOrder, "desc", "desc sorting order for second click");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter");
equal(loadFilter.sortField, "value", "sort field is provided in loadFilter");
});
test("no sorting for column with sorting = false", function() {
var $element = $("#jsGrid");
var gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorting: false }
]
};
var grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal(grid._sortField, null, "sort field is not set for the field with sorting=false");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false");
equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false");
});
test("sort accepts sorting config", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
grid.sort({ field: "value", order: "asc" });
equal(grid._sortOrder, "asc", "asc sorting order is set");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 1);
equal(gridData[1].value, 2);
equal(gridData[2].value, 3);
grid.sort({ field: 0 });
equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting");
equal(grid._sortField, grid.fields[0], "sort field is set");
equal(gridData[0].value, 3);
equal(gridData[1].value, 2);
equal(gridData[2].value, 1);
grid.sort("value", "asc");
equal(grid._sortOrder, "asc", "asc sorting order is set");
equal(grid._sortField, grid.fields[0], "sort field is set");
grid.sort(0);
equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting");
equal(grid._sortField, grid.fields[0], "sort field is set");
});
test("getSorting returns current sorting", function() {
var $element = $("#jsGrid"),
gridOptions = {
sorting: true,
data: [
{ value: 3 },
{ value: 2 },
{ value: 1 }
],
fields: [
{ name: "value", sorter: "number" }
]
},
grid = new Grid($element, gridOptions);
deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting");
grid.sort("value");
deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned");
});
test("sorting css attached correctly when a field is hidden", function() {
var $element = $("#jsGrid");
var gridOptions = {
sorting: true,
data: [],
fields: [
{ name: "field1", visible: false },
{ name: "field2" }
]
};
var grid = new Grid($element, gridOptions);
var gridData = grid.option("data");
var $th = grid._headerRow.find("th").eq(0);
$th.trigger("click");
equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field");
});
module("canceling events");
test("cancel item edit", function() {
var $element = $("#jsGrid");
var data = [{}];
var gridOptions = {
editing: true,
onItemEditing: function(e) {
e.cancel = true;
},
controller: {
loadData: function() {
return data;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.loadData();
grid.editItem(data[0]);
strictEqual(grid._editingRow, null, "no editing row");
});
test("cancel controller.loadData", function() {
var $element = $("#jsGrid");
var gridOptions = {
onDataLoading: function(e) {
e.cancel = true;
},
controller: {
loadData: function() {
return [{}];
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.loadData();
equal(grid.option("data").length, 0, "no data loaded");
});
test("cancel controller.insertItem", function() {
var $element = $("#jsGrid");
var insertedItem = null;
var gridOptions = {
onItemInserting: function(e) {
e.cancel = true;
},
controller: {
insertItem: function(item) {
insertedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem({ test: "value" });
strictEqual(insertedItem, null, "item was not inserted");
});
test("cancel controller.updateItem", function() {
var $element = $("#jsGrid");
var updatedItem = null;
var existingItem = { test: "value" };
var gridOptions = {
data: [
existingItem
],
onItemUpdating: function(e) {
e.cancel = true;
},
controller: {
updateItem: function(item) {
updatedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.updateItem(existingItem, { test: "new_value" });
strictEqual(updatedItem, null, "item was not updated");
});
test("cancel controller.deleteItem", function() {
var $element = $("#jsGrid");
var deletingItem = { test: "value" };
var deletedItem = null;
var gridOptions = {
data: [
deletingItem
],
confirmDeleting: false,
onItemDeleting: function(e) {
e.cancel = true;
},
controller: {
deleteItem: function(item) {
deletedItem = item;
}
},
fields: [
{ name: "test" }
]
};
var grid = new Grid($element, gridOptions);
grid.deleteItem(deletingItem);
strictEqual(deletedItem, null, "item was not deleted");
});
module("complex properties binding");
test("rendering", function() {
var $element = $("#jsGrid");
var gridOptions = {
loadMessage: "",
data: [
{ complexProp: { prop: "test" } }
],
fields: [
{ name: "complexProp.prop", title: "" }
]
};
new Grid($element, gridOptions);
equal($element.text(), "test", "complex property value rendered");
});
test("editing", function() {
var $element = $("#jsGrid");
var gridOptions = {
editing: true,
data: [
{ complexProp: { prop: "test" } }
],
fields: [
{ type: "text", name: "complexProp.prop" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor");
});
test("should not fail if property is absent", function() {
var $element = $("#jsGrid");
var gridOptions = {
loadMessage: "",
data: [
{ complexProp: { } }
],
fields: [
{ name: "complexProp.subprop.prop", title: "" }
]
};
new Grid($element, gridOptions);
equal($element.text(), "", "rendered empty value");
});
test("inserting", function() {
var $element = $("#jsGrid");
var insertingItem;
var gridOptions = {
inserting: true,
fields: [
{ type: "text", name: "complexProp.prop" }
],
onItemInserting: function(args) {
insertingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties");
});
test("filtering", function() {
var $element = $("#jsGrid");
var loadFilter;
var gridOptions = {
filtering: true,
fields: [
{ type: "text", name: "complexProp.prop" }
],
controller: {
loadData: function(filter) {
loadFilter = filter;
}
}
};
var grid = new Grid($element, gridOptions);
grid.fields[0].filterControl.val("test");
grid.search();
deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties");
});
test("updating", function() {
var $element = $("#jsGrid");
var updatingItem;
var gridOptions = {
editing: true,
data: [
{ complexProp: { } }
],
fields: [
{ type: "text", name: "complexProp.prop" }
],
onItemUpdating: function(args) {
updatingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test");
grid.updateItem();
deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties");
});
test("update nested prop", function() {
var $element = $("#jsGrid");
var updatingItem;
var previousItem;
var gridOptions = {
editing: true,
data: [
{ prop: { subprop1: "test1", subprop2: "test2" } }
],
fields: [
{ type: "text", name: "prop.subprop1" },
{ type: "text", name: "prop.subprop2" }
],
onItemUpdating: function(args) {
updatingItem = args.item;
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("new_test1");
grid.updateItem();
var expectedUpdatingItem = {
prop: {
subprop1: "new_test1",
subprop2: "test2"
}
};
deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties");
});
test("updating deeply nested prop", function() {
var $element = $("#jsGrid");
var updatingItem;
var previousItem;
var gridOptions = {
editing: true,
data: [
{ complexProp: { subprop1: { another_prop: "test" } } }
],
fields: [
{ type: "text", name: "complexProp.subprop1.prop1" },
{ type: "text", name: "complexProp.subprop1.subprop2.prop12" }
],
onItemUpdating: function(args) {
updatingItem = $.extend(true, {}, args.item);
previousItem = $.extend(true, {}, args.previousItem);
}
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test1");
grid.fields[1].editControl.val("test2");
grid.updateItem();
var expectedUpdatingItem = {
complexProp: {
subprop1: {
another_prop: "test",
prop1: "test1",
subprop2: { prop12: "test2" }
}
}
};
var expectedPreviousItem = {
complexProp: {
subprop1: {
another_prop: "test"
}
}
};
deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties");
deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly");
});
module("validation");
test("insertItem should call validation.validate", function() {
var $element = $("#jsGrid");
var fieldValidationRules = { test: "value" };
var validatingArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function(args) {
validatingArgs = args;
return [];
}
},
fields: [
{ type: "text", name: "Name", validate: fieldValidationRules }
]
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem();
deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1,
row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided");
});
test("insertItem rejected when data is not valid", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.fields[0].insertControl.val("test");
grid.insertItem().done(function() {
ok(false, "insertItem should not be completed");
}).fail(function() {
ok(true, "insertItem should fail");
});
});
test("invalidClass is attached on invalid cell on inserting", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Id", visible: false },
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
var $insertCell = grid._insertRow.children().eq(0);
grid.insertItem();
ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached");
equal($insertCell.attr("title"), "Error", "cell tooltip contains error message");
});
test("onItemInvalid callback", function() {
var $element = $("#jsGrid");
var errors = ["Error"];
var onItemInvalidCalled = 0;
var onItemInvalidArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: $.noop,
onItemInvalid: function(args) {
onItemInvalidCalled++;
onItemInvalidArgs = args;
},
validation: {
validate: function(args) {
return !args.value ? errors : [];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem();
equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid");
deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }],
item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided");
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid");
});
test("invalidNotify", function() {
var $element = $("#jsGrid");
var errors = ["Error"];
var invalidNotifyCalled = 0;
var invalidNotifyArgs;
var gridOptions = {
data: [],
inserting: true,
invalidNotify: function(args) {
invalidNotifyCalled++;
invalidNotifyArgs = args;
},
validation: {
validate: function(args) {
return !args.value ? errors : [];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.insertItem();
equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid");
deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }],
row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided");
grid.fields[0].insertControl.val("test");
grid.insertItem();
equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid");
});
test("invalidMessage", function() {
var $element = $("#jsGrid");
var invalidMessage;
var originalAlert = window.alert;
window.alert = function(message) {
invalidMessage = message;
};
try {
Grid.prototype.invalidMessage = "InvalidTest";
Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] });
var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n");
equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages");
} finally {
window.alert = originalAlert;
}
});
test("updateItem should call validation.validate", function() {
var $element = $("#jsGrid");
var validatingArgs;
var gridOptions = {
data: [{ Name: "" }],
editing: true,
invalidNotify: $.noop,
validation: {
validate: function(args) {
validatingArgs = args;
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: "required" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.fields[0].editControl.val("test");
grid.updateItem();
deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0,
row: grid._getEditRow(), rules: "required" }, "validating args is provided");
});
test("invalidClass is attached on invalid cell on updating", function() {
var $element = $("#jsGrid");
var gridOptions = {
data: [{}],
editing: true,
invalidNotify: $.noop,
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", validate: true }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
var $editCell = grid._getEditRow().children().eq(0);
grid.updateItem();
ok($editCell.hasClass(grid.invalidClass), "invalid class is attached");
equal($editCell.attr("title"), "Error", "cell tooltip contains error message");
});
test("validation should ignore not editable fields", function() {
var invalidNotifyCalled = 0;
var $element = $("#jsGrid");
var validatingArgs;
var gridOptions = {
data: [{ Name: "" }],
editing: true,
invalidNotify: function() {
invalidNotifyCalled++;
},
validation: {
validate: function() {
return ["Error"];
}
},
fields: [
{ type: "text", name: "Name", editing: false, validate: "required" }
]
};
var grid = new Grid($element, gridOptions);
grid.editItem(gridOptions.data[0]);
grid.updateItem();
equal(invalidNotifyCalled, 0, "data is valid");
});
module("api");
test("reset method should go the first page when pageLoading is truned on", function() {
var items = [{ Name: "1" }, { Name: "2" }];
var $element = $("#jsGrid");
var gridOptions = {
paging: true,
pageSize: 1,
pageLoading: true,
autoload: true,
controller: {
loadData: function(args) {
return {
data: [items[args.pageIndex - 1]],
itemsCount: items.length
};
}
},
fields: [
{ type: "text", name: "Name" }
]
};
var grid = new Grid($element, gridOptions);
grid.openPage(2);
grid.reset();
equal(grid._bodyGrid.text(), "1", "grid content reset");
});
module("i18n");
test("set locale by name", function() {
jsGrid.locales.my_lang = {
grid: {
test: "test_text"
}
};
jsGrid.locale("my_lang");
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "test"), "test_text", "option localized");
});
test("set locale by config", function() {
jsGrid.locale( {
grid: {
test: "test_text"
}
});
var $element = $("#jsGrid").jsGrid({});
equal($element.jsGrid("option", "test"), "test_text", "option localized");
});
test("locale throws exception for unknown locale", function() {
throws(function() {
jsGrid.locale("unknown_lang");
}, /unknown_lang/, "locale threw an exception");
});
module("controller promise");
asyncTest("should support jQuery promise success callback", 1, function() {
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
var d = $.Deferred();
setTimeout(function() {
d.resolve(data);
start();
});
return d.promise();
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
asyncTest("should support jQuery promise fail callback", 1, function() {
var failArgs = {};
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
var d = $.Deferred();
setTimeout(function() {
d.reject(failArgs);
start();
});
return d.promise();
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.fail(function(result) {
equal(result, failArgs, "fail args provided to fail callback");
});
});
asyncTest("should support JS promise success callback", 1, function() {
if(typeof Promise === "undefined") {
ok(true, "Promise not supported");
start();
return;
}
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(data);
start();
});
});
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
asyncTest("should support JS promise fail callback", 1, function() {
if(typeof Promise === "undefined") {
ok(true, "Promise not supported");
start();
return;
}
var failArgs = {};
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(failArgs);
start();
});
});
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.fail(function(result) {
equal(result, failArgs, "fail args provided to fail callback");
});
});
test("should support non-promise result", 1, function() {
var data = [];
var gridOptions = {
autoload: false,
controller: {
loadData: function() {
return data;
}
}
};
var grid = new Grid($("#jsGrid"), gridOptions);
var promise = grid._controllerCall("loadData", {}, false, $.noop);
promise.done(function(result) {
equal(result, data, "data provided to done callback");
});
});
module("renderTemplate");
test("should pass undefined and null arguments to the renderer", function() {
var rendererArgs;
var rendererContext;
var context = {};
var renderer = function() {
rendererArgs = arguments;
rendererContext = this;
};
Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" });
equal(rendererArgs.length, 3);
strictEqual(rendererArgs[0], undefined, "undefined passed");
strictEqual(rendererArgs[1], null, "null passed");
strictEqual(rendererArgs[2], "test", "null passed");
strictEqual(rendererContext, context, "context is preserved");
});
module("Data Export", {
setup: function() {
this.exportConfig = {};
this.exportConfig.type = "csv";
this.exportConfig.subset = "all";
this.exportConfig.delimiter = "|";
this.exportConfig.includeHeaders = true;
this.exportConfig.encapsulate = true;
this.element = $("#jsGrid");
this.gridOptions = {
width: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
pageSize: 2,
data: [
{ "Name": "Otto Clay", "Country": 1, "Married": false },
{ "Name": "Connor Johnston", "Country": 2, "Married": true },
{ "Name": "Lacey Hess", "Country": 2, "Married": false },
{ "Name": "Timothy Henson", "Country": 1, "Married": true }
],
fields: [
{ name: "Name", type: "text", width: 150, validate: "required" },
{ name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{ type: "control" }
]
}
}
});
/* Base Choice Criteria
type: csv
subset: all
delimiter: |
includeHeaders: true
encapsulate: true
*/
test("Should export data: Base Choice",function(){
var grid = new Grid($(this.element), this.gridOptions);
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source");
});
test("Should export data: defaults = BCC",function(){
var grid = new Grid($(this.element), this.gridOptions);
var data = grid.exportData();
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice");
});
test("Should export data: subset=visible", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.subset = "visible";
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
//expected += '"Lacey Hess"|"Canada"|"false"\r\n';
//expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV of visible records");
});
test("Should export data: delimiter=;", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.delimiter = ";";
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name";"Country";"Is Married"\r\n';
expected += '"Otto Clay";"United States";"false"\r\n';
expected += '"Connor Johnston";"Canada";"true"\r\n';
expected += '"Lacey Hess";"Canada";"false"\r\n';
expected += '"Timothy Henson";"United States";"true"\r\n';
equal(data, expected, "Output CSV with non-default delimiter");
});
test("Should export data: headers=false", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.includeHeaders = false;
var data = grid.exportData(this.exportConfig);
var expected = "";
//expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
expected += '"Connor Johnston"|"Canada"|"true"\r\n';
expected += '"Lacey Hess"|"Canada"|"false"\r\n';
expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV without Headers");
});
test("Should export data: encapsulate=false", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig.encapsulate = false;
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += 'Name|Country|Is Married\r\n';
expected += 'Otto Clay|United States|false\r\n';
expected += 'Connor Johnston|Canada|true\r\n';
expected += 'Lacey Hess|Canada|false\r\n';
expected += 'Timothy Henson|United States|true\r\n';
equal(data, expected, "Output CSV without encapsulation");
});
test("Should export filtered data", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig['filter'] = function(item){
if (item["Name"].indexOf("O") === 0)
return true
};
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"false"\r\n';
//expected += '"Connor Johnston"|"Canada"|"true"\r\n';
//expected += '"Lacey Hess"|"Canada"|"false"\r\n';
//expected += '"Timothy Henson"|"United States"|"true"\r\n';
equal(data, expected, "Output CSV filtered to show names starting with O");
});
test("Should export data: transformed value", function(){
var grid = new Grid($(this.element), this.gridOptions);
this.exportConfig['transforms'] = {};
this.exportConfig.transforms['Married'] = function(value){
if (value === true) return "Yes"
if (value === false) return "No"
};
var data = grid.exportData(this.exportConfig);
var expected = "";
expected += '"Name"|"Country"|"Is Married"\r\n';
expected += '"Otto Clay"|"United States"|"No"\r\n';
expected += '"Connor Johnston"|"Canada"|"Yes"\r\n';
expected += '"Lacey Hess"|"Canada"|"No"\r\n';
expected += '"Timothy Henson"|"United States"|"Yes"\r\n';
equal(data, expected, "Output CSV column value transformed properly");
});
});
<MSG> Core: Hide unavalable pager nav buttons
<DFF> @@ -1371,7 +1371,8 @@ $(function() {
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current");
equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed");
- equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ...");
+ equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ...");
+ equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev");
grid.openPage(2);
equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page");
| 2 | Core: Hide unavalable pager nav buttons | 1 | .js | tests | mit | tabalinas/jsgrid |
10069260 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
onRefreshing: $.noop,
onRefreshed: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Merge branch 'master' of https://github.com/tabalinas/jsgrid
<DFF> @@ -142,6 +142,7 @@
onRefreshing: $.noop,
onRefreshed: $.noop,
+ onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
@@ -970,6 +971,10 @@
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
+
+ this._callEventHandler(this.onPageChanged, {
+ pageIndex: pageIndex
+ });
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
| 5 | Merge branch 'master' of https://github.com/tabalinas/jsgrid | 0 | .js | core | mit | tabalinas/jsgrid |
10069261 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
onRefreshing: $.noop,
onRefreshed: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Merge branch 'master' of https://github.com/tabalinas/jsgrid
<DFF> @@ -142,6 +142,7 @@
onRefreshing: $.noop,
onRefreshed: $.noop,
+ onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
@@ -970,6 +971,10 @@
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
+
+ this._callEventHandler(this.onPageChanged, {
+ pageIndex: pageIndex
+ });
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
| 5 | Merge branch 'master' of https://github.com/tabalinas/jsgrid | 0 | .js | core | mit | tabalinas/jsgrid |
10069262 | <NME> db.js
<BEF> (function() {
var db = {
loadData: function(filter) {
return $.grep(this.clients, function(client) {
return (!filter.Name || client.Name.indexOf(filter.Name) > -1)
&& (filter.Age === undefined || client.Age === filter.Age)
&& (!filter.Address || client.Address.indexOf(filter.Address) > -1)
&& (!filter.Country || client.Country === filter.Country)
&& (filter.Married === undefined || client.Married === filter.Married);
});
},
insertItem: function(insertingClient) {
this.clients.push(insertingClient);
},
updateItem: function(updatingClient) { },
deleteItem: function(deletingClient) {
var clientIndex = $.inArray(deletingClient, this.clients);
this.clients.splice(clientIndex, 1);
}
};
window.db = db;
db.countries = [
{ Name: "(Select)", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 },
{ Name: "France", Id: 4 },
{ Name: "Brazil", Id: 5 },
{ Name: "China", Id: 6 },
{ Name: "Russia", Id: 7 }
];
db.clients = [
{
"Name": "Otto Clay",
"Age": 61,
"Country": 6,
"Address": "Ap #897-1459 Quam Avenue",
"Married": false
},
{
"Name": "Connor Johnston",
"Age": 73,
"Country": 7,
"Address": "Ap #370-4647 Dis Av.",
"Married": false
},
{
"Name": "Lacey Hess",
"Age": 29,
"Country": 7,
"Address": "Ap #365-8835 Integer St.",
"Married": false
},
{
"Name": "Timothy Henson",
"Age": 78,
"Country": 1,
"Address": "911-5143 Luctus Ave",
"Married": false
},
{
"Name": "Ramona Benton",
"Age": 43,
"Country": 5,
"Address": "Ap #614-689 Vehicula Street",
"Married": true
},
{
"Name": "Ezra Tillman",
"Age": 51,
"Country": 1,
"Address": "P.O. Box 738, 7583 Quisque St.",
"Married": true
},
{
"Name": "Dante Carter",
"Age": 59,
"Country": 1,
"Address": "P.O. Box 976, 6316 Lorem, St.",
"Married": false
},
{
"Name": "Christopher Mcclure",
"Age": 58,
"Country": 1,
"Address": "847-4303 Dictum Av.",
"Married": true
},
{
"Name": "Ruby Rocha",
"Age": 62,
"Country": 2,
"Address": "5212 Sagittis Ave",
"Married": false
},
{
"Name": "Imelda Hardin",
"Age": 39,
"Country": 5,
"Address": "719-7009 Auctor Av.",
"Married": false
},
{
"Name": "Jonah Johns",
"Age": 28,
"Country": 5,
"Address": "P.O. Box 939, 9310 A Ave",
"Married": false
},
{
"Name": "Herman Rosa",
"Age": 49,
"Country": 7,
"Address": "718-7162 Molestie Av.",
"Married": true
},
{
"Name": "Arthur Gay",
"Age": 20,
"Country": 7,
"Address": "5497 Neque Street",
"Married": false
},
{
"Name": "Xena Wilkerson",
"Age": 63,
"Country": 1,
"Address": "Ap #303-6974 Proin Street",
"Married": true
},
{
"Name": "Lilah Atkins",
"Age": 33,
"Country": 5,
"Address": "622-8602 Gravida Ave",
"Married": true
},
{
"Name": "Malik Shepard",
"Age": 59,
"Country": 1,
"Address": "967-5176 Tincidunt Av.",
"Married": false
},
{
"Name": "Keely Silva",
"Age": 24,
"Country": 1,
"Address": "P.O. Box 153, 8995 Praesent Ave",
"Married": false
},
{
"Name": "Hunter Pate",
"Age": 73,
"Country": 7,
"Address": "P.O. Box 771, 7599 Ante, Road",
"Married": false
},
{
"Name": "Mikayla Roach",
"Age": 55,
"Country": 5,
"Address": "Ap #438-9886 Donec Rd.",
"Married": true
},
{
"Name": "Upton Joseph",
"Age": 48,
"Country": 4,
"Address": "Ap #896-7592 Habitant St.",
"Married": true
},
{
"Name": "Jeanette Pate",
"Age": 59,
"Country": 2,
"Address": "P.O. Box 177, 7584 Amet, St.",
"Married": false
},
{
"Name": "Kaden Hernandez",
"Age": 79,
"Country": 3,
"Address": "366 Ut St.",
"Married": true
},
{
"Name": "Kenyon Stevens",
"Age": 20,
"Country": 3,
"Address": "P.O. Box 704, 4580 Gravida Rd.",
"Married": false
},
{
"Name": "Jerome Harper",
"Age": 31,
"Country": 5,
"Address": "2464 Porttitor Road",
"Married": false
},
{
"Name": "Jelani Patel",
"Age": 36,
"Country": 2,
"Address": "P.O. Box 541, 5805 Nec Av.",
"Married": true
},
{
"Name": "Keaton Oconnor",
"Age": 21,
"Country": 1,
"Address": "Ap #657-1093 Nec, Street",
"Married": false
},
{
"Name": "Bree Johnston",
"Age": 31,
"Country": 2,
"Address": "372-5942 Vulputate Avenue",
"Married": false
},
{
"Name": "Maisie Hodges",
"Age": 70,
"Country": 7,
"Address": "P.O. Box 445, 3880 Odio, Rd.",
"Married": false
},
{
"Name": "Kuame Calhoun",
"Age": 39,
"Country": 2,
"Address": "P.O. Box 609, 4105 Rutrum St.",
"Married": true
},
{
"Name": "Carlos Cameron",
"Age": 38,
"Country": 5,
"Address": "Ap #215-5386 A, Avenue",
"Married": false
},
{
"Name": "Fulton Parsons",
"Age": 25,
"Country": 7,
"Address": "P.O. Box 523, 3705 Sed Rd.",
"Married": false
},
{
"Name": "Wallace Christian",
"Age": 43,
"Country": 3,
"Address": "416-8816 Mauris Avenue",
"Married": true
},
{
"Name": "Caryn Maldonado",
"Age": 40,
"Country": 1,
"Address": "108-282 Nonummy Ave",
"Married": false
},
{
"Name": "Whilemina Frank",
"Age": 20,
"Country": 7,
"Address": "P.O. Box 681, 3938 Egestas. Av.",
"Married": true
},
{
"Name": "Emery Moon",
"Age": 41,
"Country": 4,
"Address": "Ap #717-8556 Non Road",
"Married": true
},
{
"Name": "Price Watkins",
"Age": 35,
"Country": 4,
"Address": "832-7810 Nunc Rd.",
"Married": false
},
{
"Name": "Lydia Castillo",
"Age": 59,
"Country": 7,
"Address": "5280 Placerat, Ave",
"Married": true
},
{
"Name": "Lawrence Conway",
"Age": 53,
"Country": 1,
"Address": "Ap #452-2808 Imperdiet St.",
"Married": false
},
{
"Name": "Kalia Nicholson",
"Age": 67,
"Country": 5,
"Address": "P.O. Box 871, 3023 Tellus Road",
"Married": true
},
{
"Name": "Brielle Baxter",
"Age": 45,
"Country": 3,
"Address": "Ap #822-9526 Ut, Road",
"Married": true
},
{
"Name": "Valentine Brady",
"Age": 72,
"Country": 7,
"Address": "8014 Enim. Road",
"Married": true
},
{
"Name": "Rebecca Gardner",
"Age": 57,
"Country": 4,
"Address": "8655 Arcu. Road",
"Married": true
},
{
"Name": "Vladimir Tate",
"Age": 26,
"Country": 1,
"Address": "130-1291 Non, Rd.",
"Married": true
},
{
"Name": "Vernon Hays",
"Age": 56,
"Country": 4,
"Address": "964-5552 In Rd.",
"Married": true
},
{
"Name": "Allegra Hull",
"Age": 22,
"Country": 4,
"Address": "245-8891 Donec St.",
"Married": true
},
{
"Name": "Hu Hendrix",
"Age": 65,
"Country": 7,
"Address": "428-5404 Tempus Ave",
"Married": true
},
{
"Name": "Kenyon Battle",
"Age": 32,
"Country": 2,
"Address": "921-6804 Lectus St.",
"Married": false
},
{
"Name": "Gloria Nielsen",
"Age": 24,
"Country": 4,
"Address": "Ap #275-4345 Lorem, Street",
"Married": true
},
{
"Name": "Illiana Kidd",
"Age": 59,
"Country": 2,
"Address": "7618 Lacus. Av.",
"Married": false
},
{
"Name": "Adria Todd",
"Age": 68,
"Country": 6,
"Address": "1889 Tincidunt Road",
"Married": false
},
{
"Name": "Kirsten Mayo",
"Age": 71,
"Country": 1,
"Address": "100-8640 Orci, Avenue",
"Married": false
},
{
"Name": "Willa Hobbs",
"Age": 60,
"Country": 6,
"Address": "P.O. Box 323, 158 Tristique St.",
"Married": false
},
{
"Name": "Alexis Clements",
"Age": 69,
"Country": 5,
"Address": "P.O. Box 176, 5107 Proin Rd.",
"Married": false
},
{
"Name": "Akeem Conrad",
"Age": 60,
"Country": 2,
"Address": "282-495 Sed Ave",
"Married": true
},
{
"Name": "Montana Silva",
"Age": 79,
"Country": 6,
"Address": "P.O. Box 120, 9766 Consectetuer St.",
"Married": false
},
{
"Name": "Kaseem Hensley",
"Age": 77,
"Country": 6,
"Address": "Ap #510-8903 Mauris. Av.",
"Married": true
},
{
"Name": "Christopher Morton",
"Age": 35,
"Country": 5,
"Address": "P.O. Box 234, 3651 Sodales Avenue",
"Married": false
},
{
"Name": "Wade Fernandez",
"Age": 49,
"Country": 6,
"Address": "740-5059 Dolor. Road",
"Married": true
},
{
"Name": "Illiana Kirby",
"Age": 31,
"Country": 2,
"Address": "527-3553 Mi Ave",
"Married": false
},
{
"Name": "Kimberley Hurley",
"Age": 65,
"Country": 5,
"Address": "P.O. Box 637, 9915 Dictum St.",
"Married": false
},
{
"Name": "Arthur Olsen",
"Age": 74,
"Country": 5,
"Address": "887-5080 Eget St.",
"Married": false
},
{
"Name": "Brody Potts",
"Age": 59,
"Country": 2,
"Address": "Ap #577-7690 Sem Road",
"Married": false
},
{
"Name": "Dillon Ford",
"Age": 60,
"Country": 1,
"Address": "Ap #885-9289 A, Av.",
"Married": true
},
{
"Name": "Hannah Juarez",
"Age": 61,
"Country": 2,
"Address": "4744 Sapien, Rd.",
"Married": true
},
{
"Name": "Vincent Shaffer",
"Age": 25,
"Country": 2,
"Address": "9203 Nunc St.",
"Married": true
},
{
"Name": "George Holt",
"Age": 27,
"Country": 6,
"Address": "4162 Cras Rd.",
"Married": false
},
{
"Name": "Tobias Bartlett",
"Age": 74,
"Country": 4,
"Address": "792-6145 Mauris St.",
"Married": true
},
{
"Name": "Xavier Hooper",
"Age": 35,
"Country": 1,
"Address": "879-5026 Interdum. Rd.",
"Married": false
},
{
"Name": "Declan Dorsey",
"Age": 31,
"Country": 2,
"Address": "Ap #926-4171 Aenean Road",
"Married": true
},
{
"Name": "Clementine Tran",
"Age": 43,
"Country": 4,
"Address": "P.O. Box 176, 9865 Eu Rd.",
"Married": true
},
{
"Name": "Pamela Moody",
"Age": 55,
"Country": 6,
"Address": "622-6233 Luctus Rd.",
"Married": true
},
{
"Name": "Julie Leon",
"Age": 43,
"Country": 6,
"Address": "Ap #915-6782 Sem Av.",
"Married": true
},
{
"Name": "Shana Nolan",
"Age": 79,
"Country": 5,
"Address": "P.O. Box 603, 899 Eu St.",
"Married": false
},
{
"Name": "Vaughan Moody",
"Age": 37,
"Country": 5,
"Address": "880 Erat Rd.",
"Married": false
},
{
"Name": "Randall Reeves",
"Age": 44,
"Country": 3,
"Address": "1819 Non Street",
"Married": false
},
{
"Name": "Dominic Raymond",
"Age": 68,
"Country": 1,
"Address": "Ap #689-4874 Nisi Rd.",
"Married": true
},
{
"Name": "Lev Pugh",
"Age": 69,
"Country": 5,
"Address": "Ap #433-6844 Auctor Avenue",
"Married": true
},
{
"Name": "Desiree Hughes",
"Age": 80,
"Country": 4,
"Address": "605-6645 Fermentum Avenue",
"Married": true
},
{
"Name": "Idona Oneill",
"Age": 23,
"Country": 7,
"Address": "751-8148 Aliquam Avenue",
"Married": true
},
{
"Name": "Lani Mayo",
"Age": 76,
"Country": 1,
"Address": "635-2704 Tristique St.",
"Married": true
},
{
"Name": "Cathleen Bonner",
"Age": 40,
"Country": 1,
"Address": "916-2910 Dolor Av.",
"Married": false
},
{
"Name": "Sydney Murray",
"Age": 44,
"Country": 5,
"Address": "835-2330 Fringilla St.",
"Married": false
},
{
"Name": "Brenna Rodriguez",
"Age": 77,
"Country": 6,
"Address": "3687 Imperdiet Av.",
"Married": true
},
{
"Name": "Alfreda Mcdaniel",
"Age": 38,
"Country": 7,
"Address": "745-8221 Aliquet Rd.",
"Married": true
},
{
"Name": "Zachery Atkins",
"Age": 30,
"Country": 1,
"Address": "549-2208 Auctor. Road",
"Married": true
},
{
"Name": "Amelia Rich",
"Age": 56,
"Country": 4,
"Address": "P.O. Box 734, 4717 Nunc Rd.",
"Married": false
},
{
"Name": "Kiayada Witt",
"Age": 62,
"Country": 3,
"Address": "Ap #735-3421 Malesuada Avenue",
"Married": false
},
{
"Name": "Lysandra Pierce",
"Age": 36,
"Country": 1,
"Address": "Ap #146-2835 Curabitur St.",
"Married": true
},
{
"Name": "Cara Rios",
"Age": 58,
"Country": 4,
"Address": "Ap #562-7811 Quam. Ave",
"Married": true
},
{
"Name": "Austin Andrews",
"Age": 55,
"Country": 7,
"Address": "P.O. Box 274, 5505 Sociis Rd.",
"Married": false
},
{
"Name": "Lillian Peterson",
"Age": 39,
"Country": 2,
"Address": "6212 A Avenue",
"Married": false
},
{
"Name": "Adria Beach",
"Age": 29,
"Country": 2,
"Address": "P.O. Box 183, 2717 Nunc Avenue",
"Married": true
},
{
"Name": "Oleg Durham",
"Age": 80,
"Country": 4,
"Address": "931-3208 Nunc Rd.",
"Married": false
},
{
"Name": "Casey Reese",
"Age": 60,
"Country": 4,
"Address": "383-3675 Ultrices, St.",
"Married": false
},
{
"Name": "Kane Burnett",
"Age": 80,
"Country": 1,
"Address": "759-8212 Dolor. Ave",
"Married": false
},
{
"Name": "Stewart Wilson",
"Age": 46,
"Country": 7,
"Address": "718-7845 Sagittis. Av.",
"Married": false
},
{
"Name": "Charity Holcomb",
"Age": 31,
"Country": 6,
"Address": "641-7892 Enim. Ave",
"Married": false
},
{
"Name": "Kyra Cummings",
"Age": 43,
"Country": 4,
"Address": "P.O. Box 702, 6621 Mus. Av.",
"Married": false
},
{
"Name": "Stuart Wallace",
"Age": 25,
"Country": 7,
"Address": "648-4990 Sed Rd.",
"Married": true
},
{
"Name": "Carter Clarke",
"Age": 59,
"Country": 6,
"Address": "Ap #547-2921 A Street",
"Married": false
}
];
db.users = [
{
"ID": "x",
"Account": "A758A693-0302-03D1-AE53-EEFE22855556",
"Name": "Carson Kelley",
"RegisterDate": "2002-04-20T22:55:52-07:00"
},
{
"Account": "D89FF524-1233-0CE7-C9E1-56EFF017A321",
"Name": "Prescott Griffin",
"RegisterDate": "2011-02-22T05:59:55-08:00"
},
{
"Account": "06FAAD9A-5114-08F6-D60C-961B2528B4F0",
"Name": "Amir Saunders",
"RegisterDate": "2014-08-13T09:17:49-07:00"
},
{
"Account": "EED7653D-7DD9-A722-64A8-36A55ECDBE77",
"Name": "Derek Thornton",
"RegisterDate": "2012-02-27T01:31:07-08:00"
},
{
"Account": "2A2E6D40-FEBD-C643-A751-9AB4CAF1E2F6",
"Name": "Fletcher Romero",
"RegisterDate": "2010-06-25T15:49:54-07:00"
},
{
"Account": "3978F8FA-DFF0-DA0E-0A5D-EB9D281A3286",
"Name": "Thaddeus Stein",
"RegisterDate": "2013-11-10T07:29:41-08:00"
},
{
"Account": "658DBF5A-176E-569A-9273-74FB5F69FA42",
"Name": "Nash Knapp",
"RegisterDate": "2005-06-24T09:11:19-07:00"
},
{
"Account": "76D2EE4B-7A73-1212-F6F2-957EF8C1F907",
"Name": "Quamar Vega",
"RegisterDate": "2011-04-13T20:06:29-07:00"
},
{
"Account": "00E46809-A595-CE82-C5B4-D1CAEB7E3E58",
"Name": "Philip Galloway",
"RegisterDate": "2008-08-21T18:59:38-07:00"
},
{
"Account": "C196781C-DDCC-AF83-DDC2-CA3E851A47A0",
"Name": "Mason French",
"RegisterDate": "2000-11-15T00:38:37-08:00"
},
{
"Account": "5911F201-818A-B393-5888-13157CE0D63F",
"Name": "Ross Cortez",
"RegisterDate": "2010-05-27T17:35:32-07:00"
},
{
"Account": "B8BB78F9-E1A1-A956-086F-E12B6FE168B6",
"Name": "Logan King",
"RegisterDate": "2003-07-08T16:58:06-07:00"
},
{
"Account": "06F636C3-9599-1A2D-5FD5-86B24ADDE626",
"Name": "Cedric Leblanc",
"RegisterDate": "2011-06-30T14:30:10-07:00"
},
{
"Account": "FE880CDD-F6E7-75CB-743C-64C6DE192412",
"Name": "Simon Sullivan",
"RegisterDate": "2013-06-11T16:35:07-07:00"
},
{
"Account": "BBEDD673-E2C1-4872-A5D3-C4EBD4BE0A12",
"Name": "Jamal West",
"RegisterDate": "2001-03-16T20:18:29-08:00"
},
{
"Account": "19BC22FA-C52E-0CC6-9552-10365C755FAC",
"Name": "Hector Morales",
"RegisterDate": "2012-11-01T01:56:34-07:00"
},
{
"Account": "A8292214-2C13-5989-3419-6B83DD637D6C",
"Name": "Herrod Hart",
"RegisterDate": "2008-03-13T19:21:04-07:00"
},
{
"Account": "0285564B-F447-0E7F-EAA1-7FB8F9C453C8",
"Name": "Clark Maxwell",
"RegisterDate": "2004-08-05T08:22:24-07:00"
},
{
"Account": "EA78F076-4F6E-4228-268C-1F51272498AE",
"Name": "Reuben Walter",
"RegisterDate": "2011-01-23T01:55:59-08:00"
},
{
"Account": "6A88C194-EA21-426F-4FE2-F2AE33F51793",
"Name": "Ira Ingram",
"RegisterDate": "2008-08-15T05:57:46-07:00"
},
{
"Account": "4275E873-439C-AD26-56B3-8715E336508E",
"Name": "Damian Morrow",
"RegisterDate": "2015-09-13T01:50:55-07:00"
},
{
"Account": "A0D733C4-9070-B8D6-4387-D44F0BA515BE",
"Name": "Macon Farrell",
"RegisterDate": "2011-03-14T05:41:40-07:00"
},
{
"Account": "B3683DE8-C2FA-7CA0-A8A6-8FA7E954F90A",
"Name": "Joel Galloway",
"RegisterDate": "2003-02-03T04:19:01-08:00"
},
{
"Account": "01D95A8E-91BC-2050-F5D0-4437AAFFD11F",
"Name": "Rigel Horton",
"RegisterDate": "2015-06-20T11:53:11-07:00"
},
{
"Account": "F0D12CC0-31AC-A82E-FD73-EEEFDBD21A36",
"Name": "Sylvester Gaines",
"RegisterDate": "2004-03-12T09:57:13-08:00"
},
{
"Account": "874FCC49-9A61-71BC-2F4E-2CE88348AD7B",
"Name": "Abbot Mckay",
"RegisterDate": "2008-12-26T20:42:57-08:00"
},
{
"Account": "B8DA1912-20A0-FB6E-0031-5F88FD63EF90",
"Name": "Solomon Green",
"RegisterDate": "2013-09-04T01:44:47-07:00"
}
];
}());
<MSG> Demos: Empty country name is empty string
<DFF> @@ -29,7 +29,7 @@
db.countries = [
- { Name: "(Select)", Id: 0 },
+ { Name: "", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 },
| 1 | Demos: Empty country name is empty string | 1 | .js | js | mit | tabalinas/jsgrid |
10069263 | <NME> db.js
<BEF> (function() {
var db = {
loadData: function(filter) {
return $.grep(this.clients, function(client) {
return (!filter.Name || client.Name.indexOf(filter.Name) > -1)
&& (filter.Age === undefined || client.Age === filter.Age)
&& (!filter.Address || client.Address.indexOf(filter.Address) > -1)
&& (!filter.Country || client.Country === filter.Country)
&& (filter.Married === undefined || client.Married === filter.Married);
});
},
insertItem: function(insertingClient) {
this.clients.push(insertingClient);
},
updateItem: function(updatingClient) { },
deleteItem: function(deletingClient) {
var clientIndex = $.inArray(deletingClient, this.clients);
this.clients.splice(clientIndex, 1);
}
};
window.db = db;
db.countries = [
{ Name: "(Select)", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 },
{ Name: "France", Id: 4 },
{ Name: "Brazil", Id: 5 },
{ Name: "China", Id: 6 },
{ Name: "Russia", Id: 7 }
];
db.clients = [
{
"Name": "Otto Clay",
"Age": 61,
"Country": 6,
"Address": "Ap #897-1459 Quam Avenue",
"Married": false
},
{
"Name": "Connor Johnston",
"Age": 73,
"Country": 7,
"Address": "Ap #370-4647 Dis Av.",
"Married": false
},
{
"Name": "Lacey Hess",
"Age": 29,
"Country": 7,
"Address": "Ap #365-8835 Integer St.",
"Married": false
},
{
"Name": "Timothy Henson",
"Age": 78,
"Country": 1,
"Address": "911-5143 Luctus Ave",
"Married": false
},
{
"Name": "Ramona Benton",
"Age": 43,
"Country": 5,
"Address": "Ap #614-689 Vehicula Street",
"Married": true
},
{
"Name": "Ezra Tillman",
"Age": 51,
"Country": 1,
"Address": "P.O. Box 738, 7583 Quisque St.",
"Married": true
},
{
"Name": "Dante Carter",
"Age": 59,
"Country": 1,
"Address": "P.O. Box 976, 6316 Lorem, St.",
"Married": false
},
{
"Name": "Christopher Mcclure",
"Age": 58,
"Country": 1,
"Address": "847-4303 Dictum Av.",
"Married": true
},
{
"Name": "Ruby Rocha",
"Age": 62,
"Country": 2,
"Address": "5212 Sagittis Ave",
"Married": false
},
{
"Name": "Imelda Hardin",
"Age": 39,
"Country": 5,
"Address": "719-7009 Auctor Av.",
"Married": false
},
{
"Name": "Jonah Johns",
"Age": 28,
"Country": 5,
"Address": "P.O. Box 939, 9310 A Ave",
"Married": false
},
{
"Name": "Herman Rosa",
"Age": 49,
"Country": 7,
"Address": "718-7162 Molestie Av.",
"Married": true
},
{
"Name": "Arthur Gay",
"Age": 20,
"Country": 7,
"Address": "5497 Neque Street",
"Married": false
},
{
"Name": "Xena Wilkerson",
"Age": 63,
"Country": 1,
"Address": "Ap #303-6974 Proin Street",
"Married": true
},
{
"Name": "Lilah Atkins",
"Age": 33,
"Country": 5,
"Address": "622-8602 Gravida Ave",
"Married": true
},
{
"Name": "Malik Shepard",
"Age": 59,
"Country": 1,
"Address": "967-5176 Tincidunt Av.",
"Married": false
},
{
"Name": "Keely Silva",
"Age": 24,
"Country": 1,
"Address": "P.O. Box 153, 8995 Praesent Ave",
"Married": false
},
{
"Name": "Hunter Pate",
"Age": 73,
"Country": 7,
"Address": "P.O. Box 771, 7599 Ante, Road",
"Married": false
},
{
"Name": "Mikayla Roach",
"Age": 55,
"Country": 5,
"Address": "Ap #438-9886 Donec Rd.",
"Married": true
},
{
"Name": "Upton Joseph",
"Age": 48,
"Country": 4,
"Address": "Ap #896-7592 Habitant St.",
"Married": true
},
{
"Name": "Jeanette Pate",
"Age": 59,
"Country": 2,
"Address": "P.O. Box 177, 7584 Amet, St.",
"Married": false
},
{
"Name": "Kaden Hernandez",
"Age": 79,
"Country": 3,
"Address": "366 Ut St.",
"Married": true
},
{
"Name": "Kenyon Stevens",
"Age": 20,
"Country": 3,
"Address": "P.O. Box 704, 4580 Gravida Rd.",
"Married": false
},
{
"Name": "Jerome Harper",
"Age": 31,
"Country": 5,
"Address": "2464 Porttitor Road",
"Married": false
},
{
"Name": "Jelani Patel",
"Age": 36,
"Country": 2,
"Address": "P.O. Box 541, 5805 Nec Av.",
"Married": true
},
{
"Name": "Keaton Oconnor",
"Age": 21,
"Country": 1,
"Address": "Ap #657-1093 Nec, Street",
"Married": false
},
{
"Name": "Bree Johnston",
"Age": 31,
"Country": 2,
"Address": "372-5942 Vulputate Avenue",
"Married": false
},
{
"Name": "Maisie Hodges",
"Age": 70,
"Country": 7,
"Address": "P.O. Box 445, 3880 Odio, Rd.",
"Married": false
},
{
"Name": "Kuame Calhoun",
"Age": 39,
"Country": 2,
"Address": "P.O. Box 609, 4105 Rutrum St.",
"Married": true
},
{
"Name": "Carlos Cameron",
"Age": 38,
"Country": 5,
"Address": "Ap #215-5386 A, Avenue",
"Married": false
},
{
"Name": "Fulton Parsons",
"Age": 25,
"Country": 7,
"Address": "P.O. Box 523, 3705 Sed Rd.",
"Married": false
},
{
"Name": "Wallace Christian",
"Age": 43,
"Country": 3,
"Address": "416-8816 Mauris Avenue",
"Married": true
},
{
"Name": "Caryn Maldonado",
"Age": 40,
"Country": 1,
"Address": "108-282 Nonummy Ave",
"Married": false
},
{
"Name": "Whilemina Frank",
"Age": 20,
"Country": 7,
"Address": "P.O. Box 681, 3938 Egestas. Av.",
"Married": true
},
{
"Name": "Emery Moon",
"Age": 41,
"Country": 4,
"Address": "Ap #717-8556 Non Road",
"Married": true
},
{
"Name": "Price Watkins",
"Age": 35,
"Country": 4,
"Address": "832-7810 Nunc Rd.",
"Married": false
},
{
"Name": "Lydia Castillo",
"Age": 59,
"Country": 7,
"Address": "5280 Placerat, Ave",
"Married": true
},
{
"Name": "Lawrence Conway",
"Age": 53,
"Country": 1,
"Address": "Ap #452-2808 Imperdiet St.",
"Married": false
},
{
"Name": "Kalia Nicholson",
"Age": 67,
"Country": 5,
"Address": "P.O. Box 871, 3023 Tellus Road",
"Married": true
},
{
"Name": "Brielle Baxter",
"Age": 45,
"Country": 3,
"Address": "Ap #822-9526 Ut, Road",
"Married": true
},
{
"Name": "Valentine Brady",
"Age": 72,
"Country": 7,
"Address": "8014 Enim. Road",
"Married": true
},
{
"Name": "Rebecca Gardner",
"Age": 57,
"Country": 4,
"Address": "8655 Arcu. Road",
"Married": true
},
{
"Name": "Vladimir Tate",
"Age": 26,
"Country": 1,
"Address": "130-1291 Non, Rd.",
"Married": true
},
{
"Name": "Vernon Hays",
"Age": 56,
"Country": 4,
"Address": "964-5552 In Rd.",
"Married": true
},
{
"Name": "Allegra Hull",
"Age": 22,
"Country": 4,
"Address": "245-8891 Donec St.",
"Married": true
},
{
"Name": "Hu Hendrix",
"Age": 65,
"Country": 7,
"Address": "428-5404 Tempus Ave",
"Married": true
},
{
"Name": "Kenyon Battle",
"Age": 32,
"Country": 2,
"Address": "921-6804 Lectus St.",
"Married": false
},
{
"Name": "Gloria Nielsen",
"Age": 24,
"Country": 4,
"Address": "Ap #275-4345 Lorem, Street",
"Married": true
},
{
"Name": "Illiana Kidd",
"Age": 59,
"Country": 2,
"Address": "7618 Lacus. Av.",
"Married": false
},
{
"Name": "Adria Todd",
"Age": 68,
"Country": 6,
"Address": "1889 Tincidunt Road",
"Married": false
},
{
"Name": "Kirsten Mayo",
"Age": 71,
"Country": 1,
"Address": "100-8640 Orci, Avenue",
"Married": false
},
{
"Name": "Willa Hobbs",
"Age": 60,
"Country": 6,
"Address": "P.O. Box 323, 158 Tristique St.",
"Married": false
},
{
"Name": "Alexis Clements",
"Age": 69,
"Country": 5,
"Address": "P.O. Box 176, 5107 Proin Rd.",
"Married": false
},
{
"Name": "Akeem Conrad",
"Age": 60,
"Country": 2,
"Address": "282-495 Sed Ave",
"Married": true
},
{
"Name": "Montana Silva",
"Age": 79,
"Country": 6,
"Address": "P.O. Box 120, 9766 Consectetuer St.",
"Married": false
},
{
"Name": "Kaseem Hensley",
"Age": 77,
"Country": 6,
"Address": "Ap #510-8903 Mauris. Av.",
"Married": true
},
{
"Name": "Christopher Morton",
"Age": 35,
"Country": 5,
"Address": "P.O. Box 234, 3651 Sodales Avenue",
"Married": false
},
{
"Name": "Wade Fernandez",
"Age": 49,
"Country": 6,
"Address": "740-5059 Dolor. Road",
"Married": true
},
{
"Name": "Illiana Kirby",
"Age": 31,
"Country": 2,
"Address": "527-3553 Mi Ave",
"Married": false
},
{
"Name": "Kimberley Hurley",
"Age": 65,
"Country": 5,
"Address": "P.O. Box 637, 9915 Dictum St.",
"Married": false
},
{
"Name": "Arthur Olsen",
"Age": 74,
"Country": 5,
"Address": "887-5080 Eget St.",
"Married": false
},
{
"Name": "Brody Potts",
"Age": 59,
"Country": 2,
"Address": "Ap #577-7690 Sem Road",
"Married": false
},
{
"Name": "Dillon Ford",
"Age": 60,
"Country": 1,
"Address": "Ap #885-9289 A, Av.",
"Married": true
},
{
"Name": "Hannah Juarez",
"Age": 61,
"Country": 2,
"Address": "4744 Sapien, Rd.",
"Married": true
},
{
"Name": "Vincent Shaffer",
"Age": 25,
"Country": 2,
"Address": "9203 Nunc St.",
"Married": true
},
{
"Name": "George Holt",
"Age": 27,
"Country": 6,
"Address": "4162 Cras Rd.",
"Married": false
},
{
"Name": "Tobias Bartlett",
"Age": 74,
"Country": 4,
"Address": "792-6145 Mauris St.",
"Married": true
},
{
"Name": "Xavier Hooper",
"Age": 35,
"Country": 1,
"Address": "879-5026 Interdum. Rd.",
"Married": false
},
{
"Name": "Declan Dorsey",
"Age": 31,
"Country": 2,
"Address": "Ap #926-4171 Aenean Road",
"Married": true
},
{
"Name": "Clementine Tran",
"Age": 43,
"Country": 4,
"Address": "P.O. Box 176, 9865 Eu Rd.",
"Married": true
},
{
"Name": "Pamela Moody",
"Age": 55,
"Country": 6,
"Address": "622-6233 Luctus Rd.",
"Married": true
},
{
"Name": "Julie Leon",
"Age": 43,
"Country": 6,
"Address": "Ap #915-6782 Sem Av.",
"Married": true
},
{
"Name": "Shana Nolan",
"Age": 79,
"Country": 5,
"Address": "P.O. Box 603, 899 Eu St.",
"Married": false
},
{
"Name": "Vaughan Moody",
"Age": 37,
"Country": 5,
"Address": "880 Erat Rd.",
"Married": false
},
{
"Name": "Randall Reeves",
"Age": 44,
"Country": 3,
"Address": "1819 Non Street",
"Married": false
},
{
"Name": "Dominic Raymond",
"Age": 68,
"Country": 1,
"Address": "Ap #689-4874 Nisi Rd.",
"Married": true
},
{
"Name": "Lev Pugh",
"Age": 69,
"Country": 5,
"Address": "Ap #433-6844 Auctor Avenue",
"Married": true
},
{
"Name": "Desiree Hughes",
"Age": 80,
"Country": 4,
"Address": "605-6645 Fermentum Avenue",
"Married": true
},
{
"Name": "Idona Oneill",
"Age": 23,
"Country": 7,
"Address": "751-8148 Aliquam Avenue",
"Married": true
},
{
"Name": "Lani Mayo",
"Age": 76,
"Country": 1,
"Address": "635-2704 Tristique St.",
"Married": true
},
{
"Name": "Cathleen Bonner",
"Age": 40,
"Country": 1,
"Address": "916-2910 Dolor Av.",
"Married": false
},
{
"Name": "Sydney Murray",
"Age": 44,
"Country": 5,
"Address": "835-2330 Fringilla St.",
"Married": false
},
{
"Name": "Brenna Rodriguez",
"Age": 77,
"Country": 6,
"Address": "3687 Imperdiet Av.",
"Married": true
},
{
"Name": "Alfreda Mcdaniel",
"Age": 38,
"Country": 7,
"Address": "745-8221 Aliquet Rd.",
"Married": true
},
{
"Name": "Zachery Atkins",
"Age": 30,
"Country": 1,
"Address": "549-2208 Auctor. Road",
"Married": true
},
{
"Name": "Amelia Rich",
"Age": 56,
"Country": 4,
"Address": "P.O. Box 734, 4717 Nunc Rd.",
"Married": false
},
{
"Name": "Kiayada Witt",
"Age": 62,
"Country": 3,
"Address": "Ap #735-3421 Malesuada Avenue",
"Married": false
},
{
"Name": "Lysandra Pierce",
"Age": 36,
"Country": 1,
"Address": "Ap #146-2835 Curabitur St.",
"Married": true
},
{
"Name": "Cara Rios",
"Age": 58,
"Country": 4,
"Address": "Ap #562-7811 Quam. Ave",
"Married": true
},
{
"Name": "Austin Andrews",
"Age": 55,
"Country": 7,
"Address": "P.O. Box 274, 5505 Sociis Rd.",
"Married": false
},
{
"Name": "Lillian Peterson",
"Age": 39,
"Country": 2,
"Address": "6212 A Avenue",
"Married": false
},
{
"Name": "Adria Beach",
"Age": 29,
"Country": 2,
"Address": "P.O. Box 183, 2717 Nunc Avenue",
"Married": true
},
{
"Name": "Oleg Durham",
"Age": 80,
"Country": 4,
"Address": "931-3208 Nunc Rd.",
"Married": false
},
{
"Name": "Casey Reese",
"Age": 60,
"Country": 4,
"Address": "383-3675 Ultrices, St.",
"Married": false
},
{
"Name": "Kane Burnett",
"Age": 80,
"Country": 1,
"Address": "759-8212 Dolor. Ave",
"Married": false
},
{
"Name": "Stewart Wilson",
"Age": 46,
"Country": 7,
"Address": "718-7845 Sagittis. Av.",
"Married": false
},
{
"Name": "Charity Holcomb",
"Age": 31,
"Country": 6,
"Address": "641-7892 Enim. Ave",
"Married": false
},
{
"Name": "Kyra Cummings",
"Age": 43,
"Country": 4,
"Address": "P.O. Box 702, 6621 Mus. Av.",
"Married": false
},
{
"Name": "Stuart Wallace",
"Age": 25,
"Country": 7,
"Address": "648-4990 Sed Rd.",
"Married": true
},
{
"Name": "Carter Clarke",
"Age": 59,
"Country": 6,
"Address": "Ap #547-2921 A Street",
"Married": false
}
];
db.users = [
{
"ID": "x",
"Account": "A758A693-0302-03D1-AE53-EEFE22855556",
"Name": "Carson Kelley",
"RegisterDate": "2002-04-20T22:55:52-07:00"
},
{
"Account": "D89FF524-1233-0CE7-C9E1-56EFF017A321",
"Name": "Prescott Griffin",
"RegisterDate": "2011-02-22T05:59:55-08:00"
},
{
"Account": "06FAAD9A-5114-08F6-D60C-961B2528B4F0",
"Name": "Amir Saunders",
"RegisterDate": "2014-08-13T09:17:49-07:00"
},
{
"Account": "EED7653D-7DD9-A722-64A8-36A55ECDBE77",
"Name": "Derek Thornton",
"RegisterDate": "2012-02-27T01:31:07-08:00"
},
{
"Account": "2A2E6D40-FEBD-C643-A751-9AB4CAF1E2F6",
"Name": "Fletcher Romero",
"RegisterDate": "2010-06-25T15:49:54-07:00"
},
{
"Account": "3978F8FA-DFF0-DA0E-0A5D-EB9D281A3286",
"Name": "Thaddeus Stein",
"RegisterDate": "2013-11-10T07:29:41-08:00"
},
{
"Account": "658DBF5A-176E-569A-9273-74FB5F69FA42",
"Name": "Nash Knapp",
"RegisterDate": "2005-06-24T09:11:19-07:00"
},
{
"Account": "76D2EE4B-7A73-1212-F6F2-957EF8C1F907",
"Name": "Quamar Vega",
"RegisterDate": "2011-04-13T20:06:29-07:00"
},
{
"Account": "00E46809-A595-CE82-C5B4-D1CAEB7E3E58",
"Name": "Philip Galloway",
"RegisterDate": "2008-08-21T18:59:38-07:00"
},
{
"Account": "C196781C-DDCC-AF83-DDC2-CA3E851A47A0",
"Name": "Mason French",
"RegisterDate": "2000-11-15T00:38:37-08:00"
},
{
"Account": "5911F201-818A-B393-5888-13157CE0D63F",
"Name": "Ross Cortez",
"RegisterDate": "2010-05-27T17:35:32-07:00"
},
{
"Account": "B8BB78F9-E1A1-A956-086F-E12B6FE168B6",
"Name": "Logan King",
"RegisterDate": "2003-07-08T16:58:06-07:00"
},
{
"Account": "06F636C3-9599-1A2D-5FD5-86B24ADDE626",
"Name": "Cedric Leblanc",
"RegisterDate": "2011-06-30T14:30:10-07:00"
},
{
"Account": "FE880CDD-F6E7-75CB-743C-64C6DE192412",
"Name": "Simon Sullivan",
"RegisterDate": "2013-06-11T16:35:07-07:00"
},
{
"Account": "BBEDD673-E2C1-4872-A5D3-C4EBD4BE0A12",
"Name": "Jamal West",
"RegisterDate": "2001-03-16T20:18:29-08:00"
},
{
"Account": "19BC22FA-C52E-0CC6-9552-10365C755FAC",
"Name": "Hector Morales",
"RegisterDate": "2012-11-01T01:56:34-07:00"
},
{
"Account": "A8292214-2C13-5989-3419-6B83DD637D6C",
"Name": "Herrod Hart",
"RegisterDate": "2008-03-13T19:21:04-07:00"
},
{
"Account": "0285564B-F447-0E7F-EAA1-7FB8F9C453C8",
"Name": "Clark Maxwell",
"RegisterDate": "2004-08-05T08:22:24-07:00"
},
{
"Account": "EA78F076-4F6E-4228-268C-1F51272498AE",
"Name": "Reuben Walter",
"RegisterDate": "2011-01-23T01:55:59-08:00"
},
{
"Account": "6A88C194-EA21-426F-4FE2-F2AE33F51793",
"Name": "Ira Ingram",
"RegisterDate": "2008-08-15T05:57:46-07:00"
},
{
"Account": "4275E873-439C-AD26-56B3-8715E336508E",
"Name": "Damian Morrow",
"RegisterDate": "2015-09-13T01:50:55-07:00"
},
{
"Account": "A0D733C4-9070-B8D6-4387-D44F0BA515BE",
"Name": "Macon Farrell",
"RegisterDate": "2011-03-14T05:41:40-07:00"
},
{
"Account": "B3683DE8-C2FA-7CA0-A8A6-8FA7E954F90A",
"Name": "Joel Galloway",
"RegisterDate": "2003-02-03T04:19:01-08:00"
},
{
"Account": "01D95A8E-91BC-2050-F5D0-4437AAFFD11F",
"Name": "Rigel Horton",
"RegisterDate": "2015-06-20T11:53:11-07:00"
},
{
"Account": "F0D12CC0-31AC-A82E-FD73-EEEFDBD21A36",
"Name": "Sylvester Gaines",
"RegisterDate": "2004-03-12T09:57:13-08:00"
},
{
"Account": "874FCC49-9A61-71BC-2F4E-2CE88348AD7B",
"Name": "Abbot Mckay",
"RegisterDate": "2008-12-26T20:42:57-08:00"
},
{
"Account": "B8DA1912-20A0-FB6E-0031-5F88FD63EF90",
"Name": "Solomon Green",
"RegisterDate": "2013-09-04T01:44:47-07:00"
}
];
}());
<MSG> Demos: Empty country name is empty string
<DFF> @@ -29,7 +29,7 @@
db.countries = [
- { Name: "(Select)", Id: 0 },
+ { Name: "", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 },
| 1 | Demos: Empty country name is empty string | 1 | .js | js | mit | tabalinas/jsgrid |
10069264 | <NME> jsgrid.sort-strategies.js
<BEF> (function(jsGrid, $, undefined) {
var sortStrategies = {
string: function(str1, str2) {
return str1.localeCompare(str2);
},
number: function(n1, n2) {
return n1 - n2;
},
date: function(dt1, dt2) {
return dt1 - dt2;
},
numberAsString: function(n1, n2) {
return parseFloat(n1) - parseFloat(n2);
}
};
jsGrid.sortStrategies = sortStrategies;
}(jsGrid, jQuery));
jsGrid.sortStrategies = sortStrategies;
}(jsGrid, jQuery));
<MSG> Merge pull request #7 from ReneHezser/master
SortStrategies: Consider null and undefined values in "string" sort strategy
<DFF> @@ -1,23 +1,32 @@
-(function(jsGrid, $, undefined) {
-
- var sortStrategies = {
- string: function(str1, str2) {
- return str1.localeCompare(str2);
- },
-
- number: function(n1, n2) {
- return n1 - n2;
- },
-
- date: function(dt1, dt2) {
- return dt1 - dt2;
- },
-
- numberAsString: function(n1, n2) {
- return parseFloat(n1) - parseFloat(n2);
- }
- };
-
- jsGrid.sortStrategies = sortStrategies;
-
+(function (jsGrid, $, undefined) {
+
+ var sortStrategies = {
+ string: function (str1, str2) {
+ if ((typeof (str1) == 'undefined' || str1 == null) && (typeof (str2) == 'undefined' || str2 == null))
+ return 0;
+
+ if (typeof (str1) == 'undefined' || str1 == null)
+ return -1;
+
+ if (typeof (str2) == 'undefined' || str2 == null)
+ return 1;
+
+ return str1.localeCompare(str2);
+ },
+
+ number: function (n1, n2) {
+ return n1 - n2;
+ },
+
+ date: function (dt1, dt2) {
+ return dt1 - dt2;
+ },
+
+ numberAsString: function (n1, n2) {
+ return parseFloat(n1) - parseFloat(n2);
+ }
+ };
+
+ jsGrid.sortStrategies = sortStrategies;
+
}(jsGrid, jQuery));
\ No newline at end of file
| 31 | Merge pull request #7 from ReneHezser/master | 22 | .js | sort-strategies | mit | tabalinas/jsgrid |
10069265 | <NME> jsgrid.sort-strategies.js
<BEF> (function(jsGrid, $, undefined) {
var sortStrategies = {
string: function(str1, str2) {
return str1.localeCompare(str2);
},
number: function(n1, n2) {
return n1 - n2;
},
date: function(dt1, dt2) {
return dt1 - dt2;
},
numberAsString: function(n1, n2) {
return parseFloat(n1) - parseFloat(n2);
}
};
jsGrid.sortStrategies = sortStrategies;
}(jsGrid, jQuery));
jsGrid.sortStrategies = sortStrategies;
}(jsGrid, jQuery));
<MSG> Merge pull request #7 from ReneHezser/master
SortStrategies: Consider null and undefined values in "string" sort strategy
<DFF> @@ -1,23 +1,32 @@
-(function(jsGrid, $, undefined) {
-
- var sortStrategies = {
- string: function(str1, str2) {
- return str1.localeCompare(str2);
- },
-
- number: function(n1, n2) {
- return n1 - n2;
- },
-
- date: function(dt1, dt2) {
- return dt1 - dt2;
- },
-
- numberAsString: function(n1, n2) {
- return parseFloat(n1) - parseFloat(n2);
- }
- };
-
- jsGrid.sortStrategies = sortStrategies;
-
+(function (jsGrid, $, undefined) {
+
+ var sortStrategies = {
+ string: function (str1, str2) {
+ if ((typeof (str1) == 'undefined' || str1 == null) && (typeof (str2) == 'undefined' || str2 == null))
+ return 0;
+
+ if (typeof (str1) == 'undefined' || str1 == null)
+ return -1;
+
+ if (typeof (str2) == 'undefined' || str2 == null)
+ return 1;
+
+ return str1.localeCompare(str2);
+ },
+
+ number: function (n1, n2) {
+ return n1 - n2;
+ },
+
+ date: function (dt1, dt2) {
+ return dt1 - dt2;
+ },
+
+ numberAsString: function (n1, n2) {
+ return parseFloat(n1) - parseFloat(n2);
+ }
+ };
+
+ jsGrid.sortStrategies = sortStrategies;
+
}(jsGrid, jQuery));
\ No newline at end of file
| 31 | Merge pull request #7 from ReneHezser/master | 22 | .js | sort-strategies | mit | tabalinas/jsgrid |
10069266 | <NME> theme.css
<BEF> .jsgrid-grid-header,
.jsgrid-grid-body,
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
.jsgrid-insert-row > .jsgrid-cell,
.jsgrid-edit-row > .jsgrid-cell {
border: 1px solid #e9e9e9;
}
.jsgrid-header-row > .jsgrid-header-cell {
border-top: 0;
}
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
border-bottom: 0;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
}
.jsgrid-header-row .jsgrid-align-right,
.jsgrid-header-row .jsgrid-align-left {
text-align: center;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-header-scrollbar {
scrollbar-arrow-color: #f1f1f1;
scrollbar-base-color: #f1f1f1;
scrollbar-3dlight-color: #f1f1f1;
scrollbar-highlight-color: #f1f1f1;
scrollbar-track-color: #f1f1f1;
scrollbar-shadow-color: #f1f1f1;
scrollbar-dark-shadow-color: #f1f1f1;
}
.jsgrid-header-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
.jsgrid-header-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
}
.jsgrid-header-sortable:hover {
cursor: pointer;
background: #fcfcfc;
}
.jsgrid-header-row .jsgrid-header-sort {
background: #c4e2ff;
}
border-top: none;
}
.jsgrid-grid-body tr:last-child td {
border-bottom: none;
}
.jsgrid-row > td {
background: #fff;
}
.jsgrid-grid-body {
border-top: none;
}
.jsgrid-cell {
border: #f3f3f3 1px solid;
}
.jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell,
.jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell {
border-top: none;
}
.jsgrid-grid-body .jsgrid-cell:first-child {
border-left: none;
}
.jsgrid-grid-body .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-alt-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-header-row > .jsgrid-header-cell {
background: #f9f9f9;
}
.jsgrid-filter-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-insert-row > .jsgrid-cell {
background: #e3ffe5;
}
.jsgrid-edit-row > .jsgrid-cell {
background: #fdffe3;
}
.jsgrid-selected-row > .jsgrid-cell {
background: #c4e2ff;
border-color: #c4e2ff;
}
.jsgrid-nodata-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-invalid input,
.jsgrid-invalid select,
.jsgrid-invalid textarea {
background: #ffe3e5;
border: 1px solid #ff808a;
}
.jsgrid-pager-current-page {
font-weight: bold;
}
.jsgrid-pager-nav-inactive-button a {
color: #d3d3d3;
}
.jsgrid-button + .jsgrid-button {
margin-left: 5px;
}
.jsgrid-button:hover {
opacity: .5;
transition: opacity 200ms linear;
}
.jsgrid .jsgrid-button {
width: 16px;
height: 16px;
border: none;
cursor: pointer;
background-image: url(icons.png);
background-repeat: no-repeat;
background-color: transparent;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) {
.jsgrid .jsgrid-button {
background-image: url(icons-2x.png);
background-size: 24px 352px;
}
}
.jsgrid .jsgrid-mode-button {
width: 24px;
height: 24px;
}
.jsgrid-mode-on-button {
opacity: .5;
}
.jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; }
.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; }
.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; }
.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; }
.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; }
.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; }
.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; }
.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; }
.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
.jsgrid-load-shader {
background: #ddd;
opacity: .5;
filter: alpha(opacity=50);
}
.jsgrid-load-panel {
width: 15em;
height: 5em;
background: #fff;
border: 1px solid #e9e9e9;
padding-top: 3em;
text-align: center;
}
.jsgrid-load-panel:before {
content: ' ';
position: absolute;
top: .5em;
left: 50%;
margin-left: -1em;
width: 2em;
height: 2em;
border: 2px solid #009a67;
border-right-color: transparent;
border-radius: 50%;
-webkit-animation: indicator 1s linear infinite;
animation: indicator 1s linear infinite;
}
@-webkit-keyframes indicator
{
from { -webkit-transform: rotate(0deg); }
50% { -webkit-transform: rotate(180deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes indicator
{
from { transform: rotate(0deg); }
50% { transform: rotate(180deg); }
to { transform: rotate(360deg); }
}
/* old IE */
.jsgrid-load-panel {
padding-top: 1.5em\9;
}
.jsgrid-load-panel:before {
display: none\9;
}
<MSG> Theme: No side borders for first and last table cells
<DFF> @@ -16,6 +16,14 @@
border-bottom: 0;
}
+.jsgrid-header-row > th:first-child, .jsgrid-filter-row > td:first-child, .jsgrid-insert-row > td:first-child {
+ border-left: none;
+}
+
+.jsgrid-header-row > th:last-child, .jsgrid-filter-row > td:last-child, .jsgrid-insert-row > td:last-child {
+ border-right: none;
+}
+
.jsgrid-grid-header {
background: #f9f9f9;
}
@@ -60,10 +68,18 @@
border-top: none;
}
+.jsgrid-grid-body tr td:first-child {
+ border-left: none;
+}
+
.jsgrid-grid-body tr:last-child td {
border-bottom: none;
}
+.jsgrid-grid-body tr td:last-child {
+ border-right: none;
+}
+
.jsgrid-row > td {
background: #fff;
}
| 16 | Theme: No side borders for first and last table cells | 0 | .css | css | mit | tabalinas/jsgrid |
10069267 | <NME> theme.css
<BEF> .jsgrid-grid-header,
.jsgrid-grid-body,
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
.jsgrid-insert-row > .jsgrid-cell,
.jsgrid-edit-row > .jsgrid-cell {
border: 1px solid #e9e9e9;
}
.jsgrid-header-row > .jsgrid-header-cell {
border-top: 0;
}
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
border-bottom: 0;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
}
.jsgrid-header-row .jsgrid-align-right,
.jsgrid-header-row .jsgrid-align-left {
text-align: center;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-header-scrollbar {
scrollbar-arrow-color: #f1f1f1;
scrollbar-base-color: #f1f1f1;
scrollbar-3dlight-color: #f1f1f1;
scrollbar-highlight-color: #f1f1f1;
scrollbar-track-color: #f1f1f1;
scrollbar-shadow-color: #f1f1f1;
scrollbar-dark-shadow-color: #f1f1f1;
}
.jsgrid-header-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
.jsgrid-header-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
}
.jsgrid-header-sortable:hover {
cursor: pointer;
background: #fcfcfc;
}
.jsgrid-header-row .jsgrid-header-sort {
background: #c4e2ff;
}
border-top: none;
}
.jsgrid-grid-body tr:last-child td {
border-bottom: none;
}
.jsgrid-row > td {
background: #fff;
}
.jsgrid-grid-body {
border-top: none;
}
.jsgrid-cell {
border: #f3f3f3 1px solid;
}
.jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell,
.jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell {
border-top: none;
}
.jsgrid-grid-body .jsgrid-cell:first-child {
border-left: none;
}
.jsgrid-grid-body .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-alt-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-header-row > .jsgrid-header-cell {
background: #f9f9f9;
}
.jsgrid-filter-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-insert-row > .jsgrid-cell {
background: #e3ffe5;
}
.jsgrid-edit-row > .jsgrid-cell {
background: #fdffe3;
}
.jsgrid-selected-row > .jsgrid-cell {
background: #c4e2ff;
border-color: #c4e2ff;
}
.jsgrid-nodata-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-invalid input,
.jsgrid-invalid select,
.jsgrid-invalid textarea {
background: #ffe3e5;
border: 1px solid #ff808a;
}
.jsgrid-pager-current-page {
font-weight: bold;
}
.jsgrid-pager-nav-inactive-button a {
color: #d3d3d3;
}
.jsgrid-button + .jsgrid-button {
margin-left: 5px;
}
.jsgrid-button:hover {
opacity: .5;
transition: opacity 200ms linear;
}
.jsgrid .jsgrid-button {
width: 16px;
height: 16px;
border: none;
cursor: pointer;
background-image: url(icons.png);
background-repeat: no-repeat;
background-color: transparent;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) {
.jsgrid .jsgrid-button {
background-image: url(icons-2x.png);
background-size: 24px 352px;
}
}
.jsgrid .jsgrid-mode-button {
width: 24px;
height: 24px;
}
.jsgrid-mode-on-button {
opacity: .5;
}
.jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; }
.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; }
.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; }
.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; }
.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; }
.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; }
.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; }
.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; }
.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
.jsgrid-load-shader {
background: #ddd;
opacity: .5;
filter: alpha(opacity=50);
}
.jsgrid-load-panel {
width: 15em;
height: 5em;
background: #fff;
border: 1px solid #e9e9e9;
padding-top: 3em;
text-align: center;
}
.jsgrid-load-panel:before {
content: ' ';
position: absolute;
top: .5em;
left: 50%;
margin-left: -1em;
width: 2em;
height: 2em;
border: 2px solid #009a67;
border-right-color: transparent;
border-radius: 50%;
-webkit-animation: indicator 1s linear infinite;
animation: indicator 1s linear infinite;
}
@-webkit-keyframes indicator
{
from { -webkit-transform: rotate(0deg); }
50% { -webkit-transform: rotate(180deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes indicator
{
from { transform: rotate(0deg); }
50% { transform: rotate(180deg); }
to { transform: rotate(360deg); }
}
/* old IE */
.jsgrid-load-panel {
padding-top: 1.5em\9;
}
.jsgrid-load-panel:before {
display: none\9;
}
<MSG> Theme: No side borders for first and last table cells
<DFF> @@ -16,6 +16,14 @@
border-bottom: 0;
}
+.jsgrid-header-row > th:first-child, .jsgrid-filter-row > td:first-child, .jsgrid-insert-row > td:first-child {
+ border-left: none;
+}
+
+.jsgrid-header-row > th:last-child, .jsgrid-filter-row > td:last-child, .jsgrid-insert-row > td:last-child {
+ border-right: none;
+}
+
.jsgrid-grid-header {
background: #f9f9f9;
}
@@ -60,10 +68,18 @@
border-top: none;
}
+.jsgrid-grid-body tr td:first-child {
+ border-left: none;
+}
+
.jsgrid-grid-body tr:last-child td {
border-bottom: none;
}
+.jsgrid-grid-body tr td:last-child {
+ border-right: none;
+}
+
.jsgrid-row > td {
background: #fff;
}
| 16 | Theme: No side borders for first and last table cells | 0 | .css | css | mit | tabalinas/jsgrid |
10069268 | <NME> LumenPassport.php
<BEF> <?php
namespace Dusterio\LumenPassport;
use Illuminate\Support\Arr;
use Laravel\Passport\Passport;
use DateTimeInterface;
use Carbon\Carbon;
use Laravel\Lumen\Application;
use Laravel\Lumen\Routing\Router;
class LumenPassport
{
/**
* Allow simultaneous logins for users
*
* @var bool
*/
public static $allowMultipleTokens = false;
/**
* The date when access tokens expire (specific per password client).
*
* @var array
*/
public static $tokensExpireAt = [];
/**
* Instruct Passport to keep revoked tokens pruned.
*/
public static function allowMultipleTokens()
{
static::$allowMultipleTokens = true;
}
/**
* Get or set when access tokens expire.
*
* @param \DateTimeInterface|null $date
* @param int $clientId
* @return \DateInterval|static
*/
public static function tokensExpireIn(DateTimeInterface $date = null, $clientId = null)
{
if (! $clientId) return Passport::tokensExpireIn($date);
if (is_null($date)) {
return isset(static::$tokensExpireAt[$clientId])
? Carbon::now()->diff(static::$tokensExpireAt[$clientId])
: Passport::tokensExpireIn();
} else {
static::$tokensExpireAt[$clientId] = $date;
}
return new static;
}
/**
* Get a Passport route registrar.
*
* @param callable|Router|Application $callback
* @param array $options
* @return RouteRegistrar
*/
public static function routes($callback = null, array $options = [])
{
if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)|(9\..*)/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
};
$defaultOptions = [
'prefix' => 'oauth',
'namespace' => '\Laravel\Passport\Http\Controllers',
];
$options = array_merge($defaultOptions, $options);
$callback->group(Arr::except($options, ['namespace']), function ($router) use ($callback, $options) {
$routes = new RouteRegistrar($router, $options);
$routes->all();
});
}
$options = array_merge($defaultOptions, $options);
$callback->group(array_except($options, ['namespace']), function ($router) use ($callback) {
$routes = new RouteRegistrar($router);
$routes->all();
});
}
<MSG> r Correct namespaces
<DFF> @@ -85,8 +85,8 @@ class LumenPassport
$options = array_merge($defaultOptions, $options);
- $callback->group(array_except($options, ['namespace']), function ($router) use ($callback) {
- $routes = new RouteRegistrar($router);
+ $callback->group(array_except($options, ['namespace']), function ($router) use ($callback, $options) {
+ $routes = new RouteRegistrar($router, $options);
$routes->all();
});
}
| 2 | r Correct namespaces | 2 | .php | php | mit | dusterio/lumen-passport |
10069269 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
pageLoading: false,
autoload: false,
controller: null,
onRefreshing: $.noop,
onRefreshed: $.noop,
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Controller by default is an object with $.noop CRUD methods
<DFF> @@ -108,7 +108,12 @@
pageLoading: false,
autoload: false,
- controller: null,
+ controller: {
+ loadData: $.noop,
+ insertItem: $.noop,
+ updateItem: $.noop,
+ deleteItem: $.noop
+ },
onRefreshing: $.noop,
onRefreshed: $.noop,
| 6 | Core: Controller by default is an object with $.noop CRUD methods | 1 | .js | core | mit | tabalinas/jsgrid |
10069270 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
pageLoading: false,
autoload: false,
controller: null,
onRefreshing: $.noop,
onRefreshed: $.noop,
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Controller by default is an object with $.noop CRUD methods
<DFF> @@ -108,7 +108,12 @@
pageLoading: false,
autoload: false,
- controller: null,
+ controller: {
+ loadData: $.noop,
+ insertItem: $.noop,
+ updateItem: $.noop,
+ deleteItem: $.noop
+ },
onRefreshing: $.noop,
onRefreshed: $.noop,
| 6 | Core: Controller by default is an object with $.noop CRUD methods | 1 | .js | core | mit | tabalinas/jsgrid |
10069271 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid._getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid._getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid._getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", align: "center" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-center"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 1, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), updated = false, updatingArgs, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); equal(grid._pagerContainer.html(), "", "pager is not rendered for single page"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ..."); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: true, pageSize: 1, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 z", "pager text follows the format specified"); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); }); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Formatting: Reformat tests code <DFF> @@ -1,1557 +1,1557 @@ -$(function() { - - var Grid = jsGrid.Grid, - - JSGRID = "JSGrid", - JSGRID_DATA_KEY = JSGRID; - - Grid.prototype.updateOnResize = false; - - | 1,557 | Formatting: Reformat tests code | 1,557 | .js | tests | mit | tabalinas/jsgrid |
10069272 | <NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid._getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid._getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid._getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", align: "center" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-center"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 1, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), updated = false, updatingArgs, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); equal(grid._pagerContainer.html(), "", "pager is not rendered for single page"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 3, "three nav buttons displayed: Next Last and ..."); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: true, pageSize: 1, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 z", "pager text follows the format specified"); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); }); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Formatting: Reformat tests code <DFF> @@ -1,1557 +1,1557 @@ -$(function() { - - var Grid = jsGrid.Grid, - - JSGRID = "JSGrid", - JSGRID_DATA_KEY = JSGRID; - - Grid.prototype.updateOnResize = false; - - | 1,557 | Formatting: Reformat tests code | 1,557 | .js | tests | mit | tabalinas/jsgrid |
10069273 | <NME> jquery.meow.js
<BEF> (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 options.icon === 'string') {
this.icon = options.icon;
}
this.duration = options.duration || 5000;
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp.toString())
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(
that.manifest.addClass('hover');
}
});
this.timeout = setTimeout(function () {
if (that.hovered !== true && typeof that === 'object') {
that.destroy();
}
}, that.duration);
this.destroy = function () {
that.manifest.find('.inner').fadeTo(400, 0, function () {
.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> added sticky meows feature with inifite timeout
<DFF> @@ -63,8 +63,11 @@
if (typeof options.icon === 'string') {
this.icon = options.icon;
}
-
- this.duration = options.duration || 5000;
+ if (options.sticky) {
+ this.duration = Infinity;
+ } else {
+ this.duration = options.duration || 5000;
+ }
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp.toString())
@@ -101,12 +104,14 @@
that.manifest.addClass('hover');
}
});
-
- this.timeout = setTimeout(function () {
- if (that.hovered !== true && typeof that === 'object') {
- that.destroy();
- }
- }, that.duration);
+
+ if (this.duration !== Infinity) {
+ this.timeout = setTimeout(function () {
+ if (that.hovered !== true && typeof that === 'object') {
+ that.destroy();
+ }
+ }, that.duration);
+ }
this.destroy = function () {
that.manifest.find('.inner').fadeTo(400, 0, function () {
| 13 | added sticky meows feature with inifite timeout | 8 | .js | meow | mit | zacstewart/Meow |
10069274 | <NME> jquery.meow.js
<BEF> (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 options.icon === 'string') {
this.icon = options.icon;
}
this.duration = options.duration || 5000;
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp.toString())
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(
that.manifest.addClass('hover');
}
});
this.timeout = setTimeout(function () {
if (that.hovered !== true && typeof that === 'object') {
that.destroy();
}
}, that.duration);
this.destroy = function () {
that.manifest.find('.inner').fadeTo(400, 0, function () {
.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> added sticky meows feature with inifite timeout
<DFF> @@ -63,8 +63,11 @@
if (typeof options.icon === 'string') {
this.icon = options.icon;
}
-
- this.duration = options.duration || 5000;
+ if (options.sticky) {
+ this.duration = Infinity;
+ } else {
+ this.duration = options.duration || 5000;
+ }
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp.toString())
@@ -101,12 +104,14 @@
that.manifest.addClass('hover');
}
});
-
- this.timeout = setTimeout(function () {
- if (that.hovered !== true && typeof that === 'object') {
- that.destroy();
- }
- }, that.duration);
+
+ if (this.duration !== Infinity) {
+ this.timeout = setTimeout(function () {
+ if (that.hovered !== true && typeof that === 'object') {
+ that.destroy();
+ }
+ }, that.duration);
+ }
this.destroy = function () {
that.manifest.find('.inner').fadeTo(400, 0, function () {
| 13 | added sticky meows feature with inifite timeout | 8 | .js | meow | mit | zacstewart/Meow |
10069275 | <NME> configuration_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
before(:each) { @config = Split::Configuration.new }
it "should provide default values" do
@config.ignore_ip_addresses.should eql([])
@config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
@config.db_failover.should be_false
@config.db_failover_on_db_error.should be_a Proc
@config.allow_multiple_experiments.should be_false
@config.enabled.should be_true
end
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")
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> split config specs into multiple tests
<DFF> @@ -4,12 +4,26 @@ describe Split::Configuration do
before(:each) { @config = Split::Configuration.new }
- it "should provide default values" do
+ it "should provide a default value for ignore_ip_addresses" do
@config.ignore_ip_addresses.should eql([])
- @config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
+ end
+
+ it "should provide default values for db failover" do
@config.db_failover.should be_false
- @config.db_failover_on_db_error.should be_a Proc
+ @config.db_failover_on_db_error.should be_a Proc
+ end
+
+ it "should not allow multiple experiments by default" do
@config.allow_multiple_experiments.should be_false
+ end
+
+ it "should be enabled by default" do
@config.enabled.should be_true
end
-end
+
+ it "should provide a default pattern for robots" do
+ %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg].each do |robot|
+ @config.robot_regex.should =~ robot
+ end
+ end
+end
\ No newline at end of file
| 18 | split config specs into multiple tests | 4 | .rb | rb | mit | splitrb/split |
10069276 | <NME> configuration_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
before(:each) { @config = Split::Configuration.new }
it "should provide default values" do
@config.ignore_ip_addresses.should eql([])
@config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
@config.db_failover.should be_false
@config.db_failover_on_db_error.should be_a Proc
@config.allow_multiple_experiments.should be_false
@config.enabled.should be_true
end
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")
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> split config specs into multiple tests
<DFF> @@ -4,12 +4,26 @@ describe Split::Configuration do
before(:each) { @config = Split::Configuration.new }
- it "should provide default values" do
+ it "should provide a default value for ignore_ip_addresses" do
@config.ignore_ip_addresses.should eql([])
- @config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
+ end
+
+ it "should provide default values for db failover" do
@config.db_failover.should be_false
- @config.db_failover_on_db_error.should be_a Proc
+ @config.db_failover_on_db_error.should be_a Proc
+ end
+
+ it "should not allow multiple experiments by default" do
@config.allow_multiple_experiments.should be_false
+ end
+
+ it "should be enabled by default" do
@config.enabled.should be_true
end
-end
+
+ it "should provide a default pattern for robots" do
+ %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg].each do |robot|
+ @config.robot_regex.should =~ robot
+ end
+ end
+end
\ No newline at end of file
| 18 | split config specs into multiple tests | 4 | .rb | rb | mit | splitrb/split |
10069277 | <NME> configuration_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
before(:each) { @config = Split::Configuration.new }
it "should provide default values" do
@config.ignore_ip_addresses.should eql([])
@config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
@config.db_failover.should be_false
@config.db_failover_on_db_error.should be_a Proc
@config.allow_multiple_experiments.should be_false
@config.enabled.should be_true
end
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")
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> split config specs into multiple tests
<DFF> @@ -4,12 +4,26 @@ describe Split::Configuration do
before(:each) { @config = Split::Configuration.new }
- it "should provide default values" do
+ it "should provide a default value for ignore_ip_addresses" do
@config.ignore_ip_addresses.should eql([])
- @config.robot_regex.should eql(/\b(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)\b/i)
+ end
+
+ it "should provide default values for db failover" do
@config.db_failover.should be_false
- @config.db_failover_on_db_error.should be_a Proc
+ @config.db_failover_on_db_error.should be_a Proc
+ end
+
+ it "should not allow multiple experiments by default" do
@config.allow_multiple_experiments.should be_false
+ end
+
+ it "should be enabled by default" do
@config.enabled.should be_true
end
-end
+
+ it "should provide a default pattern for robots" do
+ %w[Baidu Gigabot Googlebot libwww-perl lwp-trivial msnbot SiteUptime Slurp WordPress ZIBB ZyBorg].each do |robot|
+ @config.robot_regex.should =~ robot
+ end
+ end
+end
\ No newline at end of file
| 18 | split config specs into multiple tests | 4 | .rb | rb | mit | splitrb/split |
10069278 | <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
this.queue[meow.timestamp] = meow;
// 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
for (timestamp in this.queue) {
if (this.queue.hasOwnProperty(timestamp)) { size += 1; }
}
return size;
}
(function ($) {
'use strict';
var meows = {},
methods = {};
function Meow(options) {
var that = this;
this.title = options.title
this.message = options.message;
this.icon = options.icon;
this.timestamp = Date.now();
this.duration = options.duration || 2400;
this.hovered = false;
this.manifest = {};
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp)
.addClass('meow')
.html($(document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
this.manifest = $('#meow-' + this.timestamp);
if (typeof this.title === 'string') {
this.manifest.find('.inner').prepend(
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('×')
.attr('href', '#close-meow-' + that.timestamp)
.click(function (e) {
e.preventDefault();
that.destroy();
})
);
};
}
methods = {
configMessage: function (options) {
var trigger,
title,
message,
icon,
message_type,
duration;
if (typeof options.title === 'string') {
title = options.title;
}
if (typeof options.message === 'string') {
message_type = 'string';
} else if (typeof options.message === 'object') {
message_type = options.message.get(0).nodeName;
if (typeof title === 'undefined' && typeof options.message.attr('title') === 'string') {
title = options.message.attr('title');
}
}
switch (message_type) {
case 'string':
message = options.message;
break;
case 'INPUT':
case 'SELECT':
case 'TEXTAREA':
message = options.message.attr('value');
break;
default:
message = options.message.text();
break;
}
if (typeof options.icon === 'string') {
icon = options.icon;
}
duration = options.duration;
return {
trigger: trigger,
message: message,
icon: icon,
title: title,
duration: duration,
message_type: message_type
}
},
createMessage: function (options) {
var meow = new Meow(options);
meows[meow.timestampe] = meow;
}
};
$.fn.meow = function (args) {
var options,
trigger;
return this.each(function () {
if (typeof args === 'string') {
trigger = options;
} else if (typeof args === 'object') {
// set the event
if (typeof args.trigger === 'string') {
trigger = args.trigger;
}
}
if (typeof trigger === 'string') {
$(this).bind(trigger, function () {
options = methods.configMessage(args);
methods.createMessage(options);
});
} else if (typeof trigger === 'undefined') {
options = methods.configMessage(args);
methods.createMessage(options);
}
});
};
}(jQuery));
} 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> Merge branch 'refactor'
<DFF> @@ -1,7 +1,7 @@
// 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
@@ -9,10 +9,10 @@
// 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
@@ -24,26 +24,61 @@
(function ($) {
'use strict';
- var meows = {},
- methods = {};
+ var meows = {};
function Meow(options) {
- var that = this;
- this.title = options.title
- this.message = options.message;
- this.icon = options.icon;
- this.timestamp = Date.now();
- this.duration = options.duration || 2400;
- this.hovered = false;
- this.manifest = {};
+ var that = this,
+ message_type;
+ this.timestamp = Date.now(); // used to identify this meow and timeout
+ this.hovered = false; // whether mouse is over or not
+ this.manifest = {}; // stores the DOM object of this meow
+
+ meows[this.timestamp] = this;
+
+ if (typeof options.title === 'string') {
+ this.title = options.title;
+ }
+ if (typeof options.message === 'string') {
+ message_type = 'string';
+ } else if (typeof options.message === 'object') {
+ message_type = options.message.get(0).nodeName;
+ if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') {
+ this.title = options.message.attr('title');
+ }
+ }
+
+ console.log(message_type);
+ switch (message_type) {
+ case 'string':
+ this.message = options.message;
+ break;
+ case 'SELECT':
+ this.message = options.message.find('option:selected').text();
+ break;
+ case 'INPUT':
+ case 'SELECT':
+ case 'TEXTAREA':
+ this.message = options.message.attr('value');
+ break;
+ default:
+ this.message = options.message.text();
+ break;
+ }
+
+ if (typeof options.icon === 'string') {
+ this.icon = options.icon;
+ }
+
+ this.duration = options.duration || 5000;
+
$('#meows').append($(document.createElement('div'))
- .attr('id', 'meow-' + this.timestamp)
+ .attr('id', 'meow-' + this.timestamp.toString())
.addClass('meow')
.html($(document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
- this.manifest = $('#meow-' + this.timestamp);
+ this.manifest = $('#meow-' + this.timestamp.toString());
if (typeof this.title === 'string') {
this.manifest.find('.inner').prepend(
@@ -88,83 +123,10 @@
};
}
- methods = {
- configMessage: function (options) {
- var trigger,
- title,
- message,
- icon,
- message_type,
- duration;
-
- if (typeof options.title === 'string') {
- title = options.title;
- }
- if (typeof options.message === 'string') {
- message_type = 'string';
- } else if (typeof options.message === 'object') {
- message_type = options.message.get(0).nodeName;
- if (typeof title === 'undefined' && typeof options.message.attr('title') === 'string') {
- title = options.message.attr('title');
- }
- }
-
- switch (message_type) {
- case 'string':
- message = options.message;
- break;
- case 'INPUT':
- case 'SELECT':
- case 'TEXTAREA':
- message = options.message.attr('value');
- break;
- default:
- message = options.message.text();
- break;
- }
-
- if (typeof options.icon === 'string') {
- icon = options.icon;
- }
-
- duration = options.duration;
-
- return {
- trigger: trigger,
- message: message,
- icon: icon,
- title: title,
- duration: duration,
- message_type: message_type
- }
- },
- createMessage: function (options) {
- var meow = new Meow(options);
- meows[meow.timestampe] = meow;
- }
- };
-
$.fn.meow = function (args) {
- var options,
- trigger;
- return this.each(function () {
- if (typeof args === 'string') {
- trigger = options;
- } else if (typeof args === 'object') {
- // set the event
- if (typeof args.trigger === 'string') {
- trigger = args.trigger;
- }
- }
- if (typeof trigger === 'string') {
- $(this).bind(trigger, function () {
- options = methods.configMessage(args);
- methods.createMessage(options);
- });
- } else if (typeof trigger === 'undefined') {
- options = methods.configMessage(args);
- methods.createMessage(options);
- }
- });
+ new Meow(args);
+ };
+ $.meow = function (args) {
+ $.fn.meow(args);
};
}(jQuery));
\ No newline at end of file
| 54 | Merge branch 'refactor' | 92 | .js | meow | mit | zacstewart/Meow |
10069279 | <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
this.queue[meow.timestamp] = meow;
// 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
for (timestamp in this.queue) {
if (this.queue.hasOwnProperty(timestamp)) { size += 1; }
}
return size;
}
(function ($) {
'use strict';
var meows = {},
methods = {};
function Meow(options) {
var that = this;
this.title = options.title
this.message = options.message;
this.icon = options.icon;
this.timestamp = Date.now();
this.duration = options.duration || 2400;
this.hovered = false;
this.manifest = {};
$('#meows').append($(document.createElement('div'))
.attr('id', 'meow-' + this.timestamp)
.addClass('meow')
.html($(document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
this.manifest = $('#meow-' + this.timestamp);
if (typeof this.title === 'string') {
this.manifest.find('.inner').prepend(
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('×')
.attr('href', '#close-meow-' + that.timestamp)
.click(function (e) {
e.preventDefault();
that.destroy();
})
);
};
}
methods = {
configMessage: function (options) {
var trigger,
title,
message,
icon,
message_type,
duration;
if (typeof options.title === 'string') {
title = options.title;
}
if (typeof options.message === 'string') {
message_type = 'string';
} else if (typeof options.message === 'object') {
message_type = options.message.get(0).nodeName;
if (typeof title === 'undefined' && typeof options.message.attr('title') === 'string') {
title = options.message.attr('title');
}
}
switch (message_type) {
case 'string':
message = options.message;
break;
case 'INPUT':
case 'SELECT':
case 'TEXTAREA':
message = options.message.attr('value');
break;
default:
message = options.message.text();
break;
}
if (typeof options.icon === 'string') {
icon = options.icon;
}
duration = options.duration;
return {
trigger: trigger,
message: message,
icon: icon,
title: title,
duration: duration,
message_type: message_type
}
},
createMessage: function (options) {
var meow = new Meow(options);
meows[meow.timestampe] = meow;
}
};
$.fn.meow = function (args) {
var options,
trigger;
return this.each(function () {
if (typeof args === 'string') {
trigger = options;
} else if (typeof args === 'object') {
// set the event
if (typeof args.trigger === 'string') {
trigger = args.trigger;
}
}
if (typeof trigger === 'string') {
$(this).bind(trigger, function () {
options = methods.configMessage(args);
methods.createMessage(options);
});
} else if (typeof trigger === 'undefined') {
options = methods.configMessage(args);
methods.createMessage(options);
}
});
};
}(jQuery));
} 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> Merge branch 'refactor'
<DFF> @@ -1,7 +1,7 @@
// 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
@@ -9,10 +9,10 @@
// 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
@@ -24,26 +24,61 @@
(function ($) {
'use strict';
- var meows = {},
- methods = {};
+ var meows = {};
function Meow(options) {
- var that = this;
- this.title = options.title
- this.message = options.message;
- this.icon = options.icon;
- this.timestamp = Date.now();
- this.duration = options.duration || 2400;
- this.hovered = false;
- this.manifest = {};
+ var that = this,
+ message_type;
+ this.timestamp = Date.now(); // used to identify this meow and timeout
+ this.hovered = false; // whether mouse is over or not
+ this.manifest = {}; // stores the DOM object of this meow
+
+ meows[this.timestamp] = this;
+
+ if (typeof options.title === 'string') {
+ this.title = options.title;
+ }
+ if (typeof options.message === 'string') {
+ message_type = 'string';
+ } else if (typeof options.message === 'object') {
+ message_type = options.message.get(0).nodeName;
+ if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') {
+ this.title = options.message.attr('title');
+ }
+ }
+
+ console.log(message_type);
+ switch (message_type) {
+ case 'string':
+ this.message = options.message;
+ break;
+ case 'SELECT':
+ this.message = options.message.find('option:selected').text();
+ break;
+ case 'INPUT':
+ case 'SELECT':
+ case 'TEXTAREA':
+ this.message = options.message.attr('value');
+ break;
+ default:
+ this.message = options.message.text();
+ break;
+ }
+
+ if (typeof options.icon === 'string') {
+ this.icon = options.icon;
+ }
+
+ this.duration = options.duration || 5000;
+
$('#meows').append($(document.createElement('div'))
- .attr('id', 'meow-' + this.timestamp)
+ .attr('id', 'meow-' + this.timestamp.toString())
.addClass('meow')
.html($(document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
- this.manifest = $('#meow-' + this.timestamp);
+ this.manifest = $('#meow-' + this.timestamp.toString());
if (typeof this.title === 'string') {
this.manifest.find('.inner').prepend(
@@ -88,83 +123,10 @@
};
}
- methods = {
- configMessage: function (options) {
- var trigger,
- title,
- message,
- icon,
- message_type,
- duration;
-
- if (typeof options.title === 'string') {
- title = options.title;
- }
- if (typeof options.message === 'string') {
- message_type = 'string';
- } else if (typeof options.message === 'object') {
- message_type = options.message.get(0).nodeName;
- if (typeof title === 'undefined' && typeof options.message.attr('title') === 'string') {
- title = options.message.attr('title');
- }
- }
-
- switch (message_type) {
- case 'string':
- message = options.message;
- break;
- case 'INPUT':
- case 'SELECT':
- case 'TEXTAREA':
- message = options.message.attr('value');
- break;
- default:
- message = options.message.text();
- break;
- }
-
- if (typeof options.icon === 'string') {
- icon = options.icon;
- }
-
- duration = options.duration;
-
- return {
- trigger: trigger,
- message: message,
- icon: icon,
- title: title,
- duration: duration,
- message_type: message_type
- }
- },
- createMessage: function (options) {
- var meow = new Meow(options);
- meows[meow.timestampe] = meow;
- }
- };
-
$.fn.meow = function (args) {
- var options,
- trigger;
- return this.each(function () {
- if (typeof args === 'string') {
- trigger = options;
- } else if (typeof args === 'object') {
- // set the event
- if (typeof args.trigger === 'string') {
- trigger = args.trigger;
- }
- }
- if (typeof trigger === 'string') {
- $(this).bind(trigger, function () {
- options = methods.configMessage(args);
- methods.createMessage(options);
- });
- } else if (typeof trigger === 'undefined') {
- options = methods.configMessage(args);
- methods.createMessage(options);
- }
- });
+ new Meow(args);
+ };
+ $.meow = function (args) {
+ $.fn.meow(args);
};
}(jQuery));
\ No newline at end of file
| 54 | Merge branch 'refactor' | 92 | .js | meow | mit | zacstewart/Meow |
10069280 | <NME> transducers.js
<BEF>
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
iterator: symbolExists ? Symbol.iterator : '@@iterator'
};
function throwProtocolError(name, coll) {
throw new Error("don't know how to " + name + " collection: " +
coll);
}
function fulfillsProtocol(obj, name) {
if(name === 'iterator') {
// Accept ill-formed iterators that don't conform to the
// protocol by accepting just next()
return obj[protocols.iterator] || obj.next;
}
return obj[protocols[name]];
}
function getProtocolProperty(obj, name) {
return obj[protocols[name]];
}
function iterator(coll) {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
else if(isObject(coll)) {
return new ObjectIterator(coll);
}
}
function ArrayIterator(arr) {
this.arr = arr;
this.index = 0;
}
ArrayIterator.prototype.next = function() {
if(this.index < this.arr.length) {
return {
value: this.arr[this.index++],
done: false
};
}
return {
done: true
}
};
function ObjectIterator(obj) {
this.obj = obj;
this.keys = Object.keys(obj);
this.index = 0;
}
ObjectIterator.prototype.next = function() {
if(this.index < this.keys.length) {
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
}
function isNumber(x) {
return typeof x === 'number';
}
function Reduced(value) {
this['@@transducer/reduced'] = true;
this['@@transducer/value'] = value;
}
function isReduced(x) {
return (x instanceof Reduced) || (x && x['@@transducer/reduced']);
}
function deref(x) {
return x['@@transducer/value'];
}
/**
* This is for transforms that may call their nested transforms before
* Reduced-wrapping the result (e.g. "take"), to avoid nested Reduced.
*/
function ensureReduced(val) {
if(isReduced(val)) {
return val;
} else {
return new Reduced(val);
}
}
/**
* This is for tranforms that call their nested transforms when
* performing completion (like "partition"), to avoid signaling
* termination after already completing.
*/
function ensureUnreduced(v) {
if(isReduced(v)) {
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform['@@transducer/step'](result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform['@@transducer/result'](result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
result = xform['@@transducer/step'](result, val.value);
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
return xform['@@transducer/result'](result);
}
throwProtocolError('iterate', coll);
}
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
init = xform['@@transducer/init']();
}
return reduce(coll, xform, init);
}
function compose() {
var funcs = Array.prototype.slice.call(arguments);
return function(r) {
var value = r;
for(var i=funcs.length-1; i>=0; i--) {
value = funcs[i](value);
}
return value;
}
}
// transformations
function transformer(f) {
var t = {};
t['@@transducer/init'] = function() {
throw new Error('init value unavailable');
};
t['@@transducer/result'] = function(v) {
return v;
};
t['@@transducer/step'] = f;
return t;
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
else {
switch(count) {
case 1:
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
function arrayMap(arr, f, ctx) {
var index = -1;
var length = arr.length;
var result = Array(length);
f = bound(f, ctx, 2);
while (++index < length) {
result[index] = f(arr[index], index);
}
return result;
}
return this.xform.step(res, this.f(input));
};
function map(f, coll, ctx) {
//if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
//var f2 = ctx ? bound(f, ctx) : f;
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(f, coll, ctx);
}
var reducer = getReducer(coll);
var result = reducer.init();
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
result = reducer.step(result, f(cur.value));
cur = iter.next();
}
return result;
}
return function(xform) {
this.f = f;
}
Map.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Map.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Map.prototype['@@transducer/step'] = function(res, input) {
return this.xform['@@transducer/step'](res, this.f(input));
};
function map(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(coll, f, ctx);
}
return seq(coll, map(f));
}
return function(xform) {
return new Map(f, xform);
if(isArray(coll)) {
return arrayFilter(f, coll, ctx);
}
var reducer = getReducer(coll);
var result = reducer.init();
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
if(f(cur.value)) {
result = reducer.step(result, cur.value);
}
cur = iter.next();
}
return result;
}
return function(xform) {
Filter.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Filter.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Filter.prototype['@@transducer/step'] = function(res, input) {
if(this.f(input)) {
return filter(function(x) { return x != null }, coll);
}
function dedupe(coll) {
if(coll) {
var reducer = getReducer(coll);
var result = reducer.init();
var append = reducer.step;
var last;
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
if(cur.value !== last) {
result = append(result, cur.value);
}
cur = iter.next();
}
return result;
}
return function(r) {
var last;
return {
init: function() {
return r.init();
},
result: function(v) {
return r.result(v);
},
step: function(result, input) {
if(input !== last) {
last = input;
r.step(result, input);
}
return result;
}
};
}
}
function takeWhile(f, coll, ctx) {
f = bound(f, ctx);
if(coll) {
var reducer = getReducer(coll);
var result = reducer.init();
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
if(f(cur.value)) {
result = reducer.step(result, cur.value);
}
else {
break;
}
cur = iter.next();
}
return result;
}
return function(r) {
return {
init: function() {
return r.init();
},
result: function(v) {
return r.result(v);
},
step: function(result, input) {
if(f(input)) {
return r.step(result, input);
}
return new Reduced(result);
}
};
}
}
function take(n, coll) {
if(coll) {
var reducer = getReducer(coll);
var result = reducer.init();
var index = 0;
var iter = iterator(coll);
var cur = iter.next();
while(index++ < n && !cur.done) {
result = reducer.step(result, cur.value);
cur = iter.next();
}
return result;
}
return function(r) {
var i = 0;
return {
init: function() {
return r.init();
},
result: function(v) {
return r.result(v);
},
step: function(result, input) {
if(i++ < n) {
return r.step(result, input);
}
return new Reduced(result);
}
};
}
}
function drop(n, coll) {
if(coll) {
var reducer = getReducer(coll);
var result = reducer.init();
var index = 0;
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
if(++index > n) {
result = reducer.step(result, cur.value);
}
cur = iter.next();
}
return result;
}
return function(r) {
var i = 0;
return {
init: function() {
return r.init();
},
result: function(v) {
return r.result(v);
},
step: function(result, input) {
if((i++) + 1 > n) {
return r.step(result, input);
}
return result;
}
};
}
}
function dropWhile(f, coll, ctx) {
f = bound(f, ctx);
if(coll) {
var reducer = getReducer(coll);
var result = reducer.init();
var dropping = true;
var iter = iterator(coll);
var cur = iter.next();
while(!cur.done) {
if(dropping && f(cur.value)) {
cur = iter.next();
continue;
}
dropping = false;
result = reducer.step(result, cur.value);
cur = iter.next();
}
return result;
}
return function(r) {
var dropping = true;
return {
init: function() {
return r.init();
},
result: function(v) {
return r.result(v);
},
step: function(result, input, i) {
if(dropping) {
if(f(input)) {
return result;
}
else {
dropping = false;
}
}
return r.step(result, input);
}
};
}
}
function DropWhile(f, xform) {
this.xform = xform;
this.f = f;
this.dropping = true;
}
DropWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
DropWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
DropWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
}
else {
this.dropping = false;
}
}
return this.xform['@@transducer/step'](result, input);
};
function dropWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, dropWhile(f));
}
return function(xform) {
return new DropWhile(f, xform);
}
}
function Partition(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Partition.prototype['@@transducer/result'] = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));
}
return this.xform['@@transducer/result'](v);
};
Partition.prototype['@@transducer/step'] = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform['@@transducer/step'](result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
}
return function(xform) {
return new Partition(n, xform);
};
}
var NOTHING = {};
function PartitionBy(f, xform) {
// TODO: take an "opts" object that allows the user to specify
// equality
this.f = f;
this.xform = xform;
this.part = [];
this.last = NOTHING;
}
PartitionBy.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
PartitionBy.prototype['@@transducer/result'] = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l)));
}
return this.xform['@@transducer/result'](v);
};
PartitionBy.prototype['@@transducer/step'] = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform['@@transducer/step'](result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
return seq(coll, partitionBy(f));
}
return function(xform) {
return new PartitionBy(f, xform);
};
}
function Interpose(sep, xform) {
this.sep = sep;
this.xform = xform;
this.started = false;
}
Interpose.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Interpose.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Interpose.prototype['@@transducer/step'] = function(result, input) {
if (this.started) {
var withSep = this.xform['@@transducer/step'](result, this.sep);
if (isReduced(withSep)) {
return withSep;
} else {
return this.xform['@@transducer/step'](withSep, input);
}
} else {
this.started = true;
return this.xform['@@transducer/step'](result, input);
}
};
/**
* Returns a new collection containing elements of the given
* collection, separated by the specified separator. Returns a
* transducer if a collection is not provided.
*/
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
function Repeat(n, xform) {
this.xform = xform;
this.n = n;
}
Repeat.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Repeat.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Repeat.prototype['@@transducer/step'] = function(result, input) {
var n = this.n;
var r = result;
for (var i = 0; i < n; i++) {
r = this.xform['@@transducer/step'](r, input);
if (isReduced(r)) {
break;
}
}
return r;
};
/**
* Returns a new collection containing elements of the given
* collection, each repeated n times. Returns a transducer if a
* collection is not provided.
*/
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
function TakeNth(n, xform) {
this.xform = xform;
this.n = n;
this.i = -1;
}
TakeNth.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeNth.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeNth.prototype['@@transducer/step'] = function(result, input) {
this.i += 1;
if (this.i % this.n === 0) {
return this.xform['@@transducer/step'](result, input);
}
return result;
};
/**
* Returns a new collection of every nth element of the given
* collection. Returns a transducer if a collection is not provided.
*/
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
return new TakeNth(nth, xform);
};
}
return seq(coll, takeNth(nth));
}
// pure transducers (cannot take collections)
function Cat(xform) {
this.xform = xform;
}
Cat.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Cat.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Cat.prototype['@@transducer/step'] = function(result, input) {
var xform = this.xform;
var newxform = {};
newxform['@@transducer/init'] = function() {
return xform['@@transducer/init']();
};
newxform['@@transducer/result'] = function(v) {
return v;
};
newxform['@@transducer/step'] = function(result, input) {
var val = xform['@@transducer/step'](result, input);
return isReduced(val) ? deref(val) : val;
};
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
else {
var keys = Object.keys(x);
var len = keys.length;
for(var i=0; i<len; i++) {
obj[keys[i]] = x[keys[i]];
}
}
return obj;
}
var arrayReducer = {};
arrayReducer['@@transducer/init'] = function() {
return [];
};
arrayReducer['@@transducer/result'] = function(v) {
return v;
};
arrayReducer['@@transducer/step'] = push;
var objReducer = {};
objReducer['@@transducer/init'] = function() {
return {};
};
objReducer['@@transducer/result'] = function(v) {
return v;
};
objReducer['@@transducer/step'] = merge;
// building new collections
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(coll['@@transducer/step']) {
var init;
if(coll['@@transducer/init']) {
init = coll['@@transducer/init']();
}
else {
init = new coll.constructor();
}
return transduce(coll, xform, coll, init);
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(to['@@transducer/step']) {
return transduce(from,
xform,
to,
to);
}
throwProtocolError('into', to);
}
// laziness
var stepper = {};
stepper['@@transducer/result'] = function(v) {
return isReduced(v) ? deref(v) : v;
};
stepper['@@transducer/step'] = function(lt, x) {
lt.items.push(x);
return lt.rest;
};
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
Stepper.prototype['@@transducer/step'] = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform['@@transducer/result'](this);
break;
}
// step
this.xform['@@transducer/step'](lt, n.value);
}
}
function LazyTransformer(xform, coll) {
this.iter = iterator(coll);
this.items = [];
this.stepper = new Stepper(xform, iterator(coll));
}
LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
LazyTransformer.prototype.next = function() {
this['@@transducer/step']();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype['@@transducer/step'] = function() {
if(!this.items.length) {
this.stepper['@@transducer/step'](this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
Reduced: Reduced,
isReduced: isReduced,
iterator: iterator,
push: push,
merge: merge,
transduce: transduce,
seq: seq,
toArray: toArray,
toObj: toObj,
toIter: toIter,
into: into,
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
takeNth: takeNth,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
interpose: interpose,
repeat: repeat,
range: range,
LazyTransformer: LazyTransformer
};
<MSG> convert closures into objects
<DFF> @@ -241,26 +241,15 @@ Map.prototype.step = function(res, input) {
return this.xform.step(res, this.f(input));
};
-function map(f, coll, ctx) {
- //if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
- //var f2 = ctx ? bound(f, ctx) : f;
+function map(coll, f, ctx) {
+ if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(f, coll, ctx);
}
-
- var reducer = getReducer(coll);
- var result = reducer.init();
-
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- result = reducer.step(result, f(cur.value));
- cur = iter.next();
- }
- return result;
+ return seq(map(f), coll);
}
return function(xform) {
@@ -295,19 +284,7 @@ function filter(f, coll, ctx) {
if(isArray(coll)) {
return arrayFilter(f, coll, ctx);
}
-
- var reducer = getReducer(coll);
- var result = reducer.init();
-
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- if(f(cur.value)) {
- result = reducer.step(result, cur.value);
- }
- cur = iter.next();
- }
- return result;
+ return seq(filter(f), coll);
}
return function(xform) {
@@ -325,196 +302,166 @@ function keep(f, coll, ctx) {
return filter(function(x) { return x != null }, coll);
}
+function Dedupe(xform) {
+ this.xform = xform;
+ this.last = undefined;
+}
+
+Dedupe.prototype.init = function() {
+ return this.xform.init();
+};
+
+Dedupe.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+Dedupe.prototype.step = function(result, input) {
+ if(input !== this.last) {
+ this.last = input;
+ return this.xform.step(result, input);
+ }
+ return result;
+};
+
function dedupe(coll) {
if(coll) {
- var reducer = getReducer(coll);
- var result = reducer.init();
- var append = reducer.step;
-
- var last;
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- if(cur.value !== last) {
- result = append(result, cur.value);
- }
- cur = iter.next();
- }
- return result;
+ return seq(dedupe(), coll);
}
- return function(r) {
- var last;
- return {
- init: function() {
- return r.init();
- },
- result: function(v) {
- return r.result(v);
- },
- step: function(result, input) {
- if(input !== last) {
- last = input;
- r.step(result, input);
- }
- return result;
- }
- };
+ return function(xform) {
+ return new Dedupe(xform);
}
}
+function TakeWhile(f, xform) {
+ this.xform = xform;
+ this.f = f;
+}
+
+TakeWhile.prototype.init = function() {
+ return this.xform.init();
+};
+
+TakeWhile.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+TakeWhile.prototype.step = function(result, input) {
+ if(this.f(input)) {
+ return this.xform.step(result, input);
+ }
+ return new Reduced(result);
+};
+
function takeWhile(f, coll, ctx) {
f = bound(f, ctx);
if(coll) {
- var reducer = getReducer(coll);
- var result = reducer.init();
-
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- if(f(cur.value)) {
- result = reducer.step(result, cur.value);
- }
- else {
- break;
- }
- cur = iter.next();
- }
- return result;
+ return seq(takeWhile(f), coll);
}
- return function(r) {
- return {
- init: function() {
- return r.init();
- },
- result: function(v) {
- return r.result(v);
- },
- step: function(result, input) {
- if(f(input)) {
- return r.step(result, input);
- }
- return new Reduced(result);
- }
- };
+ return function(xform) {
+ return new TakeWhile(f, xform);
}
}
+function Take(n, xform) {
+ this.n = n;
+ this.i = 0;
+ this.xform = xform;
+}
+
+Take.prototype.init = function() {
+ return this.xform.init();
+};
+
+Take.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+Take.prototype.step = function(result, input) {
+ if(this.i++ < this.n) {
+ return this.xform.step(result, input);
+ }
+ return new Reduced(result);
+};
+
function take(n, coll) {
if(coll) {
- var reducer = getReducer(coll);
- var result = reducer.init();
-
- var index = 0;
- var iter = iterator(coll);
- var cur = iter.next();
- while(index++ < n && !cur.done) {
- result = reducer.step(result, cur.value);
- cur = iter.next();
- }
- return result;
+ return seq(take(n), coll);
}
- return function(r) {
- var i = 0;
- return {
- init: function() {
- return r.init();
- },
- result: function(v) {
- return r.result(v);
- },
- step: function(result, input) {
- if(i++ < n) {
- return r.step(result, input);
- }
- return new Reduced(result);
- }
- };
+ return function(xform) {
+ return new Take(n, xform);
}
}
-function drop(n, coll) {
- if(coll) {
- var reducer = getReducer(coll);
- var result = reducer.init();
+function Drop(n, xform) {
+ this.n = n;
+ this.i = 0;
+ this.xform = xform;
+}
- var index = 0;
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- if(++index > n) {
- result = reducer.step(result, cur.value);
- }
- cur = iter.next();
- }
+Drop.prototype.init = function() {
+ return this.xform.init();
+};
+
+Drop.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+Drop.prototype.step = function(result, input) {
+ if(this.i++ < this.n) {
return result;
}
+ return this.xform.step(result, input);
+};
- return function(r) {
- var i = 0;
- return {
- init: function() {
- return r.init();
- },
- result: function(v) {
- return r.result(v);
- },
- step: function(result, input) {
- if((i++) + 1 > n) {
- return r.step(result, input);
- }
- return result;
- }
- };
+function drop(n, coll) {
+ if(coll) {
+ return seq(drop(n), coll);
}
+
+ return function(xform) {
+ return new Drop(n, xform);
+ }
+}
+
+function DropWhile(f, xform) {
+ this.xform = xform;
+ this.f = f;
+ this.dropping = true;
}
+DropWhile.prototype.init = function() {
+ return this.xform.init();
+};
+
+DropWhile.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+DropWhile.prototype.step = function(result, input) {
+ if(this.dropping) {
+ if(this.f(input)) {
+ return result;
+ }
+ else {
+ this.dropping = false;
+ }
+ }
+ return this.xform.step(result, input);
+};
+
function dropWhile(f, coll, ctx) {
f = bound(f, ctx);
if(coll) {
- var reducer = getReducer(coll);
- var result = reducer.init();
-
- var dropping = true;
- var iter = iterator(coll);
- var cur = iter.next();
- while(!cur.done) {
- if(dropping && f(cur.value)) {
- cur = iter.next();
- continue;
- }
- dropping = false;
- result = reducer.step(result, cur.value);
- cur = iter.next();
- }
- return result;
+ return seq(dropWhile(f), coll);
}
- return function(r) {
- var dropping = true;
- return {
- init: function() {
- return r.init();
- },
- result: function(v) {
- return r.result(v);
- },
- step: function(result, input, i) {
- if(dropping) {
- if(f(input)) {
- return result;
- }
- else {
- dropping = false;
- }
- }
- return r.step(result, input);
- }
- };
+ return function(xform) {
+ return new DropWhile(f, xform);
}
}
| 128 | convert closures into objects | 181 | .js | js | bsd-2-clause | jlongster/transducers.js |
10069281 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "split/#{f}"
end
require 'split/engine' if defined?(Rails)
require 'redis/namespace'
module Split
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Rails 2.3.x compatibility patch.
Rails 2.3 doesn't have Engine support, so disable that and let people
add the helpers themselves via an initializer.
Based on @RyanNaughton's comments here:
https://github.com/andrew/split/issues/95
<DFF> @@ -2,7 +2,7 @@
require "split/#{f}"
end
-require 'split/engine' if defined?(Rails)
+require 'split/engine' if defined?(Rails) && Rails::VERSION::MAJOR >= 3
require 'redis/namespace'
module Split
| 1 | Rails 2.3.x compatibility patch. | 1 | .rb | rb | mit | splitrb/split |
10069282 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "split/#{f}"
end
require 'split/engine' if defined?(Rails)
require 'redis/namespace'
module Split
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Rails 2.3.x compatibility patch.
Rails 2.3 doesn't have Engine support, so disable that and let people
add the helpers themselves via an initializer.
Based on @RyanNaughton's comments here:
https://github.com/andrew/split/issues/95
<DFF> @@ -2,7 +2,7 @@
require "split/#{f}"
end
-require 'split/engine' if defined?(Rails)
+require 'split/engine' if defined?(Rails) && Rails::VERSION::MAJOR >= 3
require 'redis/namespace'
module Split
| 1 | Rails 2.3.x compatibility patch. | 1 | .rb | rb | mit | splitrb/split |
10069283 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "split/#{f}"
end
require 'split/engine' if defined?(Rails)
require 'redis/namespace'
module Split
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Rails 2.3.x compatibility patch.
Rails 2.3 doesn't have Engine support, so disable that and let people
add the helpers themselves via an initializer.
Based on @RyanNaughton's comments here:
https://github.com/andrew/split/issues/95
<DFF> @@ -2,7 +2,7 @@
require "split/#{f}"
end
-require 'split/engine' if defined?(Rails)
+require 'split/engine' if defined?(Rails) && Rails::VERSION::MAJOR >= 3
require 'redis/namespace'
module Split
| 1 | Rails 2.3.x compatibility patch. | 1 | .rb | rb | mit | splitrb/split |
10069284 | <NME> webpack.config.js
<BEF> ADDFILE
<MSG> release
<DFF> @@ -0,0 +1,19 @@
+var webpack = require('webpack');
+
+var config = {
+ cache: true,
+ entry: './transducers.js',
+ output: {
+ filename: './dist/transducers.js',
+ library: 'transducers'
+ },
+ plugins: []
+};
+
+if(process.env.NODE_ENV === 'production') {
+ config.plugins = config.plugins.concat([
+ new webpack.optimize.UglifyJsPlugin()
+ ]);
+}
+
+module.exports = config;
| 19 | release | 0 | .js | config | bsd-2-clause | jlongster/transducers.js |
10069285 | <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)
(new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
end
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
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
it "should allow the share of visitors see an alternative to be specified" do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
it 'should not increment the counter for an already-finished experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> More specs for participant counts
<DFF> @@ -49,6 +49,24 @@ describe Split::Helper do
(new_red_count + new_blue_count).should eql(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::Experiment.find_or_create('button_size', 'small', 'big')
+ lambda {
+ # User shouldn't participate in this second experiment
+ ab_test('button_size', 'small', 'big')
+ }.should_not change { e.participant_count }
+ end
+
+ it 'should not increment the counter for an ended experiment' do
+ e = Split::Experiment.find_or_create('button_size', 'small', 'big')
+ e.winner = 'small'
+ lambda {
+ a = ab_test('button_size', 'small', 'big')
+ a.should eq('small')
+ }.should_not change { e.participant_count }
+ end
+
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
@@ -161,7 +179,7 @@ describe Split::Helper do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
- it 'should not increment the counter for an already-finished experiment' do
+ it 'should not increment the counter for an ended experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
| 19 | More specs for participant counts | 1 | .rb | rb | mit | splitrb/split |
10069286 | <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)
(new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
end
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
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
it "should allow the share of visitors see an alternative to be specified" do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
it 'should not increment the counter for an already-finished experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> More specs for participant counts
<DFF> @@ -49,6 +49,24 @@ describe Split::Helper do
(new_red_count + new_blue_count).should eql(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::Experiment.find_or_create('button_size', 'small', 'big')
+ lambda {
+ # User shouldn't participate in this second experiment
+ ab_test('button_size', 'small', 'big')
+ }.should_not change { e.participant_count }
+ end
+
+ it 'should not increment the counter for an ended experiment' do
+ e = Split::Experiment.find_or_create('button_size', 'small', 'big')
+ e.winner = 'small'
+ lambda {
+ a = ab_test('button_size', 'small', 'big')
+ a.should eq('small')
+ }.should_not change { e.participant_count }
+ end
+
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
@@ -161,7 +179,7 @@ describe Split::Helper do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
- it 'should not increment the counter for an already-finished experiment' do
+ it 'should not increment the counter for an ended experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
| 19 | More specs for participant counts | 1 | .rb | rb | mit | splitrb/split |
10069287 | <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)
(new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
end
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
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
it "should allow the share of visitors see an alternative to be specified" do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
it 'should not increment the counter for an already-finished experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> More specs for participant counts
<DFF> @@ -49,6 +49,24 @@ describe Split::Helper do
(new_red_count + new_blue_count).should eql(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::Experiment.find_or_create('button_size', 'small', 'big')
+ lambda {
+ # User shouldn't participate in this second experiment
+ ab_test('button_size', 'small', 'big')
+ }.should_not change { e.participant_count }
+ end
+
+ it 'should not increment the counter for an ended experiment' do
+ e = Split::Experiment.find_or_create('button_size', 'small', 'big')
+ e.winner = 'small'
+ lambda {
+ a = ab_test('button_size', 'small', 'big')
+ a.should eq('small')
+ }.should_not change { e.participant_count }
+ end
+
it "should return the given alternative for an existing user" do
alternative = ab_test('link_color', 'blue', 'red')
repeat_alternative = ab_test('link_color', 'blue', 'red')
@@ -161,7 +179,7 @@ describe Split::Helper do
}.should_not change { Split::Alternative.new('small', 'button_size').completed_count }
end
- it 'should not increment the counter for an already-finished experiment' do
+ it 'should not increment the counter for an ended experiment' do
e = Split::Experiment.find_or_create('button_size', 'small', 'big')
e.winner = 'small'
a = ab_test('button_size', 'small', 'big')
| 19 | More specs for participant counts | 1 | .rb | rb | mit | splitrb/split |
10069288 | <NME> jquery.meow.js
<BEF> (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;
}
message,
icon;
return this.each(function () {
console.log(arguments);
if (typeof options === 'string') {
event = options;
} else if (typeof options == 'object') {
// 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('×')
.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> added better firefox 3 support
<DFF> @@ -73,7 +73,6 @@
message,
icon;
return this.each(function () {
- console.log(arguments);
if (typeof options === 'string') {
event = options;
} else if (typeof options == 'object') {
| 0 | added better firefox 3 support | 1 | .js | meow | mit | zacstewart/Meow |
10069289 | <NME> jquery.meow.js
<BEF> (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;
}
message,
icon;
return this.each(function () {
console.log(arguments);
if (typeof options === 'string') {
event = options;
} else if (typeof options == 'object') {
// 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('×')
.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> added better firefox 3 support
<DFF> @@ -73,7 +73,6 @@
message,
icon;
return this.each(function () {
- console.log(arguments);
if (typeof options === 'string') {
event = options;
} else if (typeof options == 'object') {
| 0 | added better firefox 3 support | 1 | .js | meow | mit | zacstewart/Meow |
10069290 | <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)")
@config.robot_regex.should_not =~ "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 use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> Merge pull request #140 from themgt/master
expose bots hash for editing from config block
<DFF> @@ -43,6 +43,11 @@ describe Split::Configuration do
@config.robot_regex.should_not =~ "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"
+ @config.robot_regex.should =~ "newbot"
+ end
+
it "should use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
| 5 | Merge pull request #140 from themgt/master | 0 | .rb | rb | mit | splitrb/split |
10069291 | <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)")
@config.robot_regex.should_not =~ "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 use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> Merge pull request #140 from themgt/master
expose bots hash for editing from config block
<DFF> @@ -43,6 +43,11 @@ describe Split::Configuration do
@config.robot_regex.should_not =~ "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"
+ @config.robot_regex.should =~ "newbot"
+ end
+
it "should use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
| 5 | Merge pull request #140 from themgt/master | 0 | .rb | rb | mit | splitrb/split |
10069292 | <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)")
@config.robot_regex.should_not =~ "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 use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
end
it "should use the session adapter for persistence by default" do
expect(@config.persistence).to eq(Split::Persistence::SessionAdapter)
end
it "should load a metric" do
@config.experiments = { my_experiment: { alternatives: ["control_opt", "other_opt"], metric: :my_metric } }
expect(@config.metrics).not_to be_nil
expect(@config.metrics.keys).to eq([: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 } }
expect(@config.experiment_for(:my_experiment)).to eq({ 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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: ["Control Opt", ["Alt One", "Alt Two"]] } })
end
end
context "in a configuration with metadata" do
before do
experiments_yaml = <<-eos
my_experiment:
alternatives:
- name: Control Opt
percent: 67
- name: Alt One
percent: 10
- name: Alt Two
percent: 23
metadata:
Control Opt:
text: 'Control Option'
Alt One:
text: 'Alternative One'
Alt Two:
text: 'Alternative Two'
resettable: false
eos
@config.experiments = YAML.load(experiments_yaml)
end
it "should have metadata on the experiment" do
meta = @config.normalized_experiments[:my_experiment][:metadata]
expect(meta).to_not be nil
expect(meta["Control Opt"]["text"]).to eq("Control Option")
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
expect(@config.normalized_experiments).to eq({ my_experiment: { resettable: false, alternatives: [{ "Control Opt"=>0.67 },
[{ "Alt One"=>0.1 }, { "Alt Two"=>0.23 }]] }, another_experiment: { alternatives: ["a", ["b"]] } })
end
it "should recognize metrics" do
expect(@config.metrics).not_to be_nil
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> Merge pull request #140 from themgt/master
expose bots hash for editing from config block
<DFF> @@ -43,6 +43,11 @@ describe Split::Configuration do
@config.robot_regex.should_not =~ "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"
+ @config.robot_regex.should =~ "newbot"
+ end
+
it "should use the session adapter for persistence by default" do
@config.persistence.should eq(Split::Persistence::SessionAdapter)
end
| 5 | Merge pull request #140 from themgt/master | 0 | .rb | rb | mit | splitrb/split |
10069293 | <NME> jquery.meow.js
<BEF> (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'))
if (event.type === 'mouseleave') {
that.hovered = false;
that.manifest.removeClass('hover');
if (that.timestamp + that.duration <= Date.now()) {
that.destroy();
};
} else {
that.hovered = true;
that.manifest.addClass('hover');
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');
}
}
};
$.fn.meow = function (event, options) {
var message,
icon;
return this.each(function () {
if (typeof options === 'object') {
if (typeof options.message === 'string') {
message = options.message;
} else if (typeof options.message === 'object') {
.addClass('meow')
.html($(window.document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
this.manifest = $('#meow-' + this.timestamp.toString());
if (typeof options.icon === 'string') {
icon = options.icon;
}
} else if (typeof options === 'string') {
message = options;
}
if (event && message) {
$(this).bind(event, function () {
methods.createMessage(message, icon);
});
}
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('×')
.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> improving options
<DFF> @@ -35,9 +35,9 @@
if (event.type === 'mouseleave') {
that.hovered = false;
that.manifest.removeClass('hover');
- if (that.timestamp + that.duration <= Date.now()) {
+ if (that.timestamp + that.duration <= Date.now()) {
that.destroy();
- };
+ }
} else {
that.hovered = true;
that.manifest.addClass('hover');
@@ -68,11 +68,19 @@
}
};
- $.fn.meow = function (event, options) {
- var message,
+ $.fn.meow = function (options) {
+ var trigger,
+ message,
icon;
return this.each(function () {
- if (typeof options === 'object') {
+ console.log(arguments);
+ if (typeof options === 'string') {
+ event = options;
+ } else if (typeof options == 'object') {
+ // is the message an object we need to parse or just a string?
+ if (typeof options.trigger === 'string') {
+ trigger = options.trigger;
+ }
if (typeof options.message === 'string') {
message = options.message;
} else if (typeof options.message === 'object') {
@@ -86,11 +94,9 @@
if (typeof options.icon === 'string') {
icon = options.icon;
}
- } else if (typeof options === 'string') {
- message = options;
}
- if (event && message) {
- $(this).bind(event, function () {
+ if (trigger && message) {
+ $(this).bind(trigger, function () {
methods.createMessage(message, icon);
});
}
| 15 | improving options | 9 | .js | meow | mit | zacstewart/Meow |
10069294 | <NME> jquery.meow.js
<BEF> (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'))
if (event.type === 'mouseleave') {
that.hovered = false;
that.manifest.removeClass('hover');
if (that.timestamp + that.duration <= Date.now()) {
that.destroy();
};
} else {
that.hovered = true;
that.manifest.addClass('hover');
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');
}
}
};
$.fn.meow = function (event, options) {
var message,
icon;
return this.each(function () {
if (typeof options === 'object') {
if (typeof options.message === 'string') {
message = options.message;
} else if (typeof options.message === 'object') {
.addClass('meow')
.html($(window.document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn(400));
this.manifest = $('#meow-' + this.timestamp.toString());
if (typeof options.icon === 'string') {
icon = options.icon;
}
} else if (typeof options === 'string') {
message = options;
}
if (event && message) {
$(this).bind(event, function () {
methods.createMessage(message, icon);
});
}
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('×')
.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> improving options
<DFF> @@ -35,9 +35,9 @@
if (event.type === 'mouseleave') {
that.hovered = false;
that.manifest.removeClass('hover');
- if (that.timestamp + that.duration <= Date.now()) {
+ if (that.timestamp + that.duration <= Date.now()) {
that.destroy();
- };
+ }
} else {
that.hovered = true;
that.manifest.addClass('hover');
@@ -68,11 +68,19 @@
}
};
- $.fn.meow = function (event, options) {
- var message,
+ $.fn.meow = function (options) {
+ var trigger,
+ message,
icon;
return this.each(function () {
- if (typeof options === 'object') {
+ console.log(arguments);
+ if (typeof options === 'string') {
+ event = options;
+ } else if (typeof options == 'object') {
+ // is the message an object we need to parse or just a string?
+ if (typeof options.trigger === 'string') {
+ trigger = options.trigger;
+ }
if (typeof options.message === 'string') {
message = options.message;
} else if (typeof options.message === 'object') {
@@ -86,11 +94,9 @@
if (typeof options.icon === 'string') {
icon = options.icon;
}
- } else if (typeof options === 'string') {
- message = options;
}
- if (event && message) {
- $(this).bind(event, function () {
+ if (trigger && message) {
+ $(this).bind(trigger, function () {
methods.createMessage(message, icon);
});
}
| 15 | improving options | 9 | .js | meow | mit | zacstewart/Meow |
10069295 | <NME> jquery.meow.js
<BEF> (function ($, window) {
'use strict';
var current_id = 0;
function Meow() {
this.id = 0;
this.message = '';
this.timestamp = Date.now();
this.duration = 2400;
this.draw = function() {
that = this;
console.log(this.message);
$('#meows').append($('<div id="meow-' + this.id + '">' + this.message + '</div>').hide().fadeIn(400));
setTimeout('that.destroy()', this.duration);
};
this.destroy = function( ) {
console.log('removing');
$('#meow-' + that.id).fadeOut(400, function() { $(this).remove() });
that.delete;
};
}
// 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
meows.push(meow);
current_id++;
}
}
$.fn.meow = function( event, message ) {
return this.each(function() {
if (meows.size() <= 0) {
if (typeof options.beforeCreateFirst === 'function') {
options.beforeCreateFirst.call(that);
}
}
}
}
});
};
})( jQuery );
}
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('×')
.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> stored each setTimeout instance within the meow it destroys
<DFF> @@ -3,22 +3,22 @@
var current_id = 0;
function Meow() {
+ var that = this;
this.id = 0;
this.message = '';
this.timestamp = Date.now();
this.duration = 2400;
this.draw = function() {
- that = this;
- console.log(this.message);
- $('#meows').append($('<div id="meow-' + this.id + '">' + this.message + '</div>').hide().fadeIn(400));
- setTimeout('that.destroy()', this.duration);
+ console.log(that.message);
+ $('#meows').append($('<div id="meow-' + that.id + '" class="meow">' + that.message + '</div>').hide().fadeIn(400));
+ that.timeout = setTimeout(function() { that.destroy(); }, that.duration);
};
this.destroy = function( ) {
console.log('removing');
- $('#meow-' + that.id).fadeOut(400, function() { $(this).remove() });
- that.delete;
+ console.log(that);
+ $('#meow-' + that.id).fadeOut(400, function() { $(that).remove(); });
};
}
@@ -31,7 +31,7 @@
meows.push(meow);
current_id++;
}
- }
+ };
$.fn.meow = function( event, message ) {
return this.each(function() {
@@ -44,6 +44,5 @@
}
}
});
-
};
-})( jQuery );
\ No newline at end of file
+}( jQuery ));
\ No newline at end of file
| 8 | stored each setTimeout instance within the meow it destroys | 9 | .js | meow | mit | zacstewart/Meow |
10069296 | <NME> jquery.meow.js
<BEF> (function ($, window) {
'use strict';
var current_id = 0;
function Meow() {
this.id = 0;
this.message = '';
this.timestamp = Date.now();
this.duration = 2400;
this.draw = function() {
that = this;
console.log(this.message);
$('#meows').append($('<div id="meow-' + this.id + '">' + this.message + '</div>').hide().fadeIn(400));
setTimeout('that.destroy()', this.duration);
};
this.destroy = function( ) {
console.log('removing');
$('#meow-' + that.id).fadeOut(400, function() { $(this).remove() });
that.delete;
};
}
// 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
meows.push(meow);
current_id++;
}
}
$.fn.meow = function( event, message ) {
return this.each(function() {
if (meows.size() <= 0) {
if (typeof options.beforeCreateFirst === 'function') {
options.beforeCreateFirst.call(that);
}
}
}
}
});
};
})( jQuery );
}
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('×')
.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> stored each setTimeout instance within the meow it destroys
<DFF> @@ -3,22 +3,22 @@
var current_id = 0;
function Meow() {
+ var that = this;
this.id = 0;
this.message = '';
this.timestamp = Date.now();
this.duration = 2400;
this.draw = function() {
- that = this;
- console.log(this.message);
- $('#meows').append($('<div id="meow-' + this.id + '">' + this.message + '</div>').hide().fadeIn(400));
- setTimeout('that.destroy()', this.duration);
+ console.log(that.message);
+ $('#meows').append($('<div id="meow-' + that.id + '" class="meow">' + that.message + '</div>').hide().fadeIn(400));
+ that.timeout = setTimeout(function() { that.destroy(); }, that.duration);
};
this.destroy = function( ) {
console.log('removing');
- $('#meow-' + that.id).fadeOut(400, function() { $(this).remove() });
- that.delete;
+ console.log(that);
+ $('#meow-' + that.id).fadeOut(400, function() { $(that).remove(); });
};
}
@@ -31,7 +31,7 @@
meows.push(meow);
current_id++;
}
- }
+ };
$.fn.meow = function( event, message ) {
return this.each(function() {
@@ -44,6 +44,5 @@
}
}
});
-
};
-})( jQuery );
\ No newline at end of file
+}( jQuery ));
\ No newline at end of file
| 8 | stored each setTimeout instance within the meow it destroys | 9 | .js | meow | mit | zacstewart/Meow |
10069297 | <NME> README.md
<BEF> ADDFILE
<MSG> added readme
<DFF> @@ -0,0 +1,4 @@
+jQuery Meow
+===========
+
+A plugin to provide Growl-like notifications. Will support bindings for various jQuery events and ability to 'meow' the content of a bound element (e.g. a Rails flash on load) or a message passed as an argument (e.g. button clicks).
\ No newline at end of file
| 4 | added readme | 0 | .md | md | mit | zacstewart/Meow |
10069298 | <NME> README.md
<BEF> ADDFILE
<MSG> added readme
<DFF> @@ -0,0 +1,4 @@
+jQuery Meow
+===========
+
+A plugin to provide Growl-like notifications. Will support bindings for various jQuery events and ability to 'meow' the content of a bound element (e.g. a Rails flash on load) or a message passed as an argument (e.g. button clicks).
\ No newline at end of file
| 4 | added readme | 0 | .md | md | mit | zacstewart/Meow |
10069299 | <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 = ["[email protected]"]
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 "rack-test", "~> 2.0"
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'
end
<MSG> Fix broken specs in developement environment (#557)
* Fix broken specs in development environment
<DFF> @@ -41,4 +41,5 @@ Gem::Specification.new do |s|
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', '>= 4.2'
end
| 1 | Fix broken specs in developement environment (#557) | 0 | .gemspec | gemspec | mit | splitrb/split |
10069300 | <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 = ["[email protected]"]
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 "rack-test", "~> 2.0"
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'
end
<MSG> Fix broken specs in developement environment (#557)
* Fix broken specs in development environment
<DFF> @@ -41,4 +41,5 @@ Gem::Specification.new do |s|
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', '>= 4.2'
end
| 1 | Fix broken specs in developement environment (#557) | 0 | .gemspec | gemspec | mit | splitrb/split |
10069301 | <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 = ["[email protected]"]
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 "rack-test", "~> 2.0"
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'
end
<MSG> Fix broken specs in developement environment (#557)
* Fix broken specs in development environment
<DFF> @@ -41,4 +41,5 @@ Gem::Specification.new do |s|
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', '>= 4.2'
end
| 1 | Fix broken specs in developement environment (#557) | 0 | .gemspec | gemspec | mit | splitrb/split |
10069302 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
self.experiment = attrs.delete(:experiment)
self.alternative = attrs.delete(:alternative)
self.metadata = attrs.delete(:metadata)
self.goals = attrs.delete(:goals) || []
@user = attrs.delete(:user)
@options = attrs
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Fix Layout/EndAlignment
<DFF> @@ -25,7 +25,7 @@ module Split
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
- end
+ end
end
def alternative=(alternative)
| 1 | Fix Layout/EndAlignment | 1 | .rb | rb | mit | splitrb/split |
10069303 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
self.experiment = attrs.delete(:experiment)
self.alternative = attrs.delete(:alternative)
self.metadata = attrs.delete(:metadata)
self.goals = attrs.delete(:goals) || []
@user = attrs.delete(:user)
@options = attrs
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Fix Layout/EndAlignment
<DFF> @@ -25,7 +25,7 @@ module Split
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
- end
+ end
end
def alternative=(alternative)
| 1 | Fix Layout/EndAlignment | 1 | .rb | rb | mit | splitrb/split |
10069304 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
self.experiment = attrs.delete(:experiment)
self.alternative = attrs.delete(:alternative)
self.metadata = attrs.delete(:metadata)
self.goals = attrs.delete(:goals) || []
@user = attrs.delete(:user)
@options = attrs
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Fix Layout/EndAlignment
<DFF> @@ -25,7 +25,7 @@ module Split
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
- end
+ end
end
def alternative=(alternative)
| 1 | Fix Layout/EndAlignment | 1 | .rb | rb | mit | splitrb/split |
10069305 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
get '/' do
@experiments = Split::Experiment.all
#Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
end
erb :index
end
post "/initialize_experiment" do
Split::ExperimentCatalog.find_or_create(params[:experiment]) unless params[:experiment].nil? || params[:experiment].empty?
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> Tiny whitespace fix
<DFF> @@ -16,7 +16,7 @@ module Split
get '/' do
@experiments = Split::Experiment.all
- #Display Rails Environment mode (or Rack version if not using Rails)
+ # Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
| 1 | Tiny whitespace fix | 1 | .rb | rb | mit | splitrb/split |
10069306 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
get '/' do
@experiments = Split::Experiment.all
#Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
end
erb :index
end
post "/initialize_experiment" do
Split::ExperimentCatalog.find_or_create(params[:experiment]) unless params[:experiment].nil? || params[:experiment].empty?
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> Tiny whitespace fix
<DFF> @@ -16,7 +16,7 @@ module Split
get '/' do
@experiments = Split::Experiment.all
- #Display Rails Environment mode (or Rack version if not using Rails)
+ # Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
| 1 | Tiny whitespace fix | 1 | .rb | rb | mit | splitrb/split |
10069307 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
get '/' do
@experiments = Split::Experiment.all
#Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
end
erb :index
end
post "/initialize_experiment" do
Split::ExperimentCatalog.find_or_create(params[:experiment]) unless params[:experiment].nil? || params[:experiment].empty?
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> Tiny whitespace fix
<DFF> @@ -16,7 +16,7 @@ module Split
get '/' do
@experiments = Split::Experiment.all
- #Display Rails Environment mode (or Rack version if not using Rails)
+ # Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?('Rails')
@current_env = Rails.env.titlecase
else
| 1 | Tiny whitespace fix | 1 | .rb | rb | mit | splitrb/split |
10069308 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
set :method_override, true
helpers Split::DashboardHelpers
helpers Split::DashboardPaginationHelpers
get "/" do
# Display experiments without a winner at the top of the dashboard
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
@experiment.save
redirect url('/')
end
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> we don't need to call save on an experiment when setting the winner
<DFF> @@ -33,7 +33,6 @@ module Split
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
- @experiment.save
redirect url('/')
end
| 0 | we don't need to call save on an experiment when setting the winner | 1 | .rb | rb | mit | splitrb/split |
10069309 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
set :method_override, true
helpers Split::DashboardHelpers
helpers Split::DashboardPaginationHelpers
get "/" do
# Display experiments without a winner at the top of the dashboard
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
@experiment.save
redirect url('/')
end
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> we don't need to call save on an experiment when setting the winner
<DFF> @@ -33,7 +33,6 @@ module Split
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
- @experiment.save
redirect url('/')
end
| 0 | we don't need to call save on an experiment when setting the winner | 1 | .rb | rb | mit | splitrb/split |
10069310 | <NME> dashboard.rb
<BEF> # frozen_string_literal: true
require "sinatra/base"
require "split"
require "bigdecimal"
require "split/dashboard/helpers"
require "split/dashboard/pagination_helpers"
module Split
class Dashboard < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/dashboard/views"
set :public_folder, "#{dir}/dashboard/public"
set :static, true
set :method_override, true
helpers Split::DashboardHelpers
helpers Split::DashboardPaginationHelpers
get "/" do
# Display experiments without a winner at the top of the dashboard
@experiments = Split::ExperimentCatalog.all_active_first
@unintialized_experiments = Split.configuration.experiments.keys - @experiments.map(&:name)
@metrics = Split::Metric.all
# Display Rails Environment mode (or Rack version if not using Rails)
if Object.const_defined?("Rails") && Rails.respond_to?(:env)
@current_env = Rails.env.titlecase
else
@current_env = "Rack: #{Rack.version}"
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
@experiment.save
redirect url('/')
end
redirect url("/")
end
post "/force_alternative" do
experiment = Split::ExperimentCatalog.find(params[:experiment])
alternative = Split::Alternative.new(params[:alternative], experiment.name)
cookies = JSON.parse(request.cookies["split_override"]) rescue {}
cookies[experiment.name] = alternative.name
response.set_cookie("split_override", { value: cookies.to_json, path: "/" })
redirect url("/")
end
post "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@alternative = Split::Alternative.new(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
redirect url("/")
end
post "/start" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.start
redirect url("/")
end
post "/reset" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset
redirect url("/")
end
post "/reopen" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.reset_winner
redirect url("/")
end
post "/update_cohorting" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
case params[:cohorting_action].downcase
when "enable"
@experiment.enable_cohorting
when "disable"
@experiment.disable_cohorting
end
redirect url("/")
end
delete "/experiment" do
@experiment = Split::ExperimentCatalog.find(params[:experiment])
@experiment.delete
redirect url("/")
end
end
end
<MSG> we don't need to call save on an experiment when setting the winner
<DFF> @@ -33,7 +33,6 @@ module Split
@experiment = Split::Experiment.find(params[:experiment])
@alternative = Split::Alternative.find(params[:alternative], params[:experiment])
@experiment.winner = @alternative.name
- @experiment.save
redirect url('/')
end
| 0 | we don't need to call save on an experiment when setting the winner | 1 | .rb | rb | mit | splitrb/split |
10069311 | <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 = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
s.add_dependency 'redis-namespace', '~> 1.0.3'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
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 "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Updated dependency for redis-namespace to 1.1.0
<DFF> @@ -19,7 +19,7 @@ Gem::Specification.new do |s|
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
- s.add_dependency 'redis-namespace', '~> 1.0.3'
+ s.add_dependency 'redis-namespace', '~> 1.1.0'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
| 1 | Updated dependency for redis-namespace to 1.1.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10069312 | <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 = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
s.add_dependency 'redis-namespace', '~> 1.0.3'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
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 "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Updated dependency for redis-namespace to 1.1.0
<DFF> @@ -19,7 +19,7 @@ Gem::Specification.new do |s|
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
- s.add_dependency 'redis-namespace', '~> 1.0.3'
+ s.add_dependency 'redis-namespace', '~> 1.1.0'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
| 1 | Updated dependency for redis-namespace to 1.1.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10069313 | <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 = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
s.add_dependency 'redis-namespace', '~> 1.0.3'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
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 "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Updated dependency for redis-namespace to 1.1.0
<DFF> @@ -19,7 +19,7 @@ Gem::Specification.new do |s|
s.require_paths = ["lib"]
s.add_dependency 'redis', '~> 2.1'
- s.add_dependency 'redis-namespace', '~> 1.0.3'
+ s.add_dependency 'redis-namespace', '~> 1.1.0'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_development_dependency 'rake'
| 1 | Updated dependency for redis-namespace to 1.1.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10069314 | <NME> jquery.meow.blackcat.css
<BEF> ADDFILE
<MSG> move restyle to themes folder
<DFF> @@ -0,0 +1,120 @@
+/* blackcat theme by Flip Stewart | github.com/shpoonj */
+
+.meows {
+ position: fixed;
+ top: 0;
+ right: 0;
+}
+
+.meow {
+ position: relative;
+ margin: 12px 12px 0 0;
+}
+
+.meow .inner {
+ display: block;
+ width: 280px;
+ min-height: 48px;
+ padding: 9px;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 13px;
+ line-height: 24px;
+ color: #ffffff;
+ text-shadow: 0 1px 0 #000000;
+ background: rgba(20, 20, 20, 0.8);
+ border: 2px solid rgba(255, 255, 255, 0.8);
+ -webkit-border-radius: 6px;
+ -khtml-border-radius: 6px;
+ -moz-border-radius: 6px;
+ -ms-border-radius: 6px;
+ -o-border-radius: 6px;
+ border-radius: 6px;
+ zoom: 1;
+ -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -khtml-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -moz-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -ms-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -o-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+}
+
+.meow .inner:hover {
+ background: rgba(20, 20, 20, 0.9);
+ border: 2px solid rgba(255, 255, 255, 0.9);
+}
+
+.meow .inner:hover .close {
+ position: absolute;
+ top: -6px;
+ right: -6px;
+ display: block;
+ width: 18px;
+ height: 18px;
+ font-size: 15px;
+ font-weight: bold;
+ line-height: 14px;
+ color: #fff;
+ text-align: center;
+ text-decoration: none;
+ text-shadow: 0 1px 0 #000000;
+ background: rgba(25, 25, 25, 0.8);
+ border: 2px solid rgba(255, 255, 255, 0.8);
+ -webkit-border-radius: 100%;
+ -khtml-border-radius: 100%;
+ -moz-border-radius: 100%;
+ -ms-border-radius: 100%;
+ -o-border-radius: 100%;
+ border-radius: 100%;
+ -webkit-opacity: 0.8;
+ -khtml-opacity: 0.8;
+ -moz-opacity: 0.8;
+ -ms-opacity: 0.8;
+ -o-opacity: 0.8;
+ opacity: 0.8;
+ zoom: 1;
+ -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -khtml-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -moz-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -ms-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -o-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+}
+
+.meow .inner:hover .close:hover {
+ background: rgba(25, 25, 25, 0.9);
+ border: 2px solid rgba(255, 255, 255, 0.9);
+}
+
+.meow .inner .icon {
+ float: left;
+ height: 48px;
+ min-width: 48px;
+ margin-right: 9px;
+}
+
+.meow .inner .icon img {
+ width: 48px;
+ height: 48px;
+}
+
+.meow .inner h1 {
+ margin: 0;
+ font-size: 13px;
+ font-weight: bold;
+ line-height: 24px;
+ color: #ffffff;
+ text-shadow: 0 1px 0 #000000;
+}
+
+.meow .inner .close {
+ display: none;
+}
+
+.meow .inner:after {
+ display: block;
+ height: 0;
+ clear: both;
+ line-height: 0;
+ content: "\0200";
+ visibility: hidden;
+}
| 120 | move restyle to themes folder | 0 | .css | meow | mit | zacstewart/Meow |
10069315 | <NME> jquery.meow.blackcat.css
<BEF> ADDFILE
<MSG> move restyle to themes folder
<DFF> @@ -0,0 +1,120 @@
+/* blackcat theme by Flip Stewart | github.com/shpoonj */
+
+.meows {
+ position: fixed;
+ top: 0;
+ right: 0;
+}
+
+.meow {
+ position: relative;
+ margin: 12px 12px 0 0;
+}
+
+.meow .inner {
+ display: block;
+ width: 280px;
+ min-height: 48px;
+ padding: 9px;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 13px;
+ line-height: 24px;
+ color: #ffffff;
+ text-shadow: 0 1px 0 #000000;
+ background: rgba(20, 20, 20, 0.8);
+ border: 2px solid rgba(255, 255, 255, 0.8);
+ -webkit-border-radius: 6px;
+ -khtml-border-radius: 6px;
+ -moz-border-radius: 6px;
+ -ms-border-radius: 6px;
+ -o-border-radius: 6px;
+ border-radius: 6px;
+ zoom: 1;
+ -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -khtml-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -moz-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -ms-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -o-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+}
+
+.meow .inner:hover {
+ background: rgba(20, 20, 20, 0.9);
+ border: 2px solid rgba(255, 255, 255, 0.9);
+}
+
+.meow .inner:hover .close {
+ position: absolute;
+ top: -6px;
+ right: -6px;
+ display: block;
+ width: 18px;
+ height: 18px;
+ font-size: 15px;
+ font-weight: bold;
+ line-height: 14px;
+ color: #fff;
+ text-align: center;
+ text-decoration: none;
+ text-shadow: 0 1px 0 #000000;
+ background: rgba(25, 25, 25, 0.8);
+ border: 2px solid rgba(255, 255, 255, 0.8);
+ -webkit-border-radius: 100%;
+ -khtml-border-radius: 100%;
+ -moz-border-radius: 100%;
+ -ms-border-radius: 100%;
+ -o-border-radius: 100%;
+ border-radius: 100%;
+ -webkit-opacity: 0.8;
+ -khtml-opacity: 0.8;
+ -moz-opacity: 0.8;
+ -ms-opacity: 0.8;
+ -o-opacity: 0.8;
+ opacity: 0.8;
+ zoom: 1;
+ -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -khtml-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -moz-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -ms-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ -o-box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
+}
+
+.meow .inner:hover .close:hover {
+ background: rgba(25, 25, 25, 0.9);
+ border: 2px solid rgba(255, 255, 255, 0.9);
+}
+
+.meow .inner .icon {
+ float: left;
+ height: 48px;
+ min-width: 48px;
+ margin-right: 9px;
+}
+
+.meow .inner .icon img {
+ width: 48px;
+ height: 48px;
+}
+
+.meow .inner h1 {
+ margin: 0;
+ font-size: 13px;
+ font-weight: bold;
+ line-height: 24px;
+ color: #ffffff;
+ text-shadow: 0 1px 0 #000000;
+}
+
+.meow .inner .close {
+ display: none;
+}
+
+.meow .inner:after {
+ display: block;
+ height: 0;
+ clear: both;
+ line-height: 0;
+ content: "\0200";
+ visibility: hidden;
+}
| 120 | move restyle to themes folder | 0 | .css | meow | mit | zacstewart/Meow |
10069316 | <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
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
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
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> Whitespace tweaks
<DFF> @@ -57,12 +57,12 @@ describe Split::Helper do
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
-
+
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
-
+
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
| 2 | Whitespace tweaks | 2 | .rb | rb | mit | splitrb/split |
10069317 | <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
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
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
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> Whitespace tweaks
<DFF> @@ -57,12 +57,12 @@ describe Split::Helper do
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
-
+
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
-
+
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
| 2 | Whitespace tweaks | 2 | .rb | rb | mit | splitrb/split |
10069318 | <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
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
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
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
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> Whitespace tweaks
<DFF> @@ -57,12 +57,12 @@ describe Split::Helper do
ret = ab_test('link_color', 'blue', 'red') { |alternative| "shared/#{alternative}" }
ret.should eql("shared/#{alt}")
end
-
+
it "should allow the share of visitors see an alternative to be specificed" do
ab_test('link_color', {'blue' => 0.8}, {'red' => 20})
['red', 'blue'].should include(ab_user['link_color'])
end
-
+
it "should allow alternative weighting interface as a single hash" do
ab_test('link_color', 'blue' => 0.01, 'red' => 0.2)
experiment = Split::Experiment.find('link_color')
| 2 | Whitespace tweaks | 2 | .rb | rb | mit | splitrb/split |
10069319 | <NME> style.css
<BEF> html {
background: #efefef;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 13px;
}
body {
padding: 0 10px;
margin: 10px auto 0;
max-width:800px;
}
.header {
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#576a76),
color-stop(100%,#4d5256));
background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);
background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);
background: linear-gradient(top, #576a76 0%, #414e58 100%);
border-bottom: 1px solid #fff;
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
border-top-left-radius: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius:5px;
border-top-right-radius: 5px;
overflow:hidden;
padding: 10px 5%;
text-shadow:0 1px 0 #000;
}
.header h1 {
color: #eee;
float:left;
font-size:1.2em;
font-weight:normal;
margin:2px 30px 0 0;
}
.header ul li {
display: inline;
}
.header ul li a {
color: #eee;
text-decoration: none;
margin-right: 10px;
display: inline-block;
padding: 4px 8px;
-moz-border-radius: 10px;
-webkit-border-radius:10px;
border-radius: 10px;
}
.header ul li a:hover {
background: rgba(255,255,255,0.1);
}
.header ul li a:active {
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
}
.header ul li.current a {
background: rgba(255,255,255,0.1);
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
color: #fff;
}
.header p.environment {
clear: both;
padding: 10px 0 0 0;
color: #BBB;
font-style: italic;
float: right;
}
#main {
padding: 10px 5%;
background: #f9f9f9;
border:1px solid #ccc;
border-top:none;
-moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);
-webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);
box-shadow: 0 3px 10px rgba(0,0,0,0.2);
overflow: hidden;
}
#main .logo {
float: right;
margin: 10px;
}
#main span.hl {
background: #efefef;
padding: 2px;
}
#main h1 {
margin: 10px 0;
font-size: 190%;
font-weight: bold;
color: #0080FF;
}
#main table {
width: 100%;
margin:0 0 10px;
}
#main table tr td, #main table tr th {
border-bottom: 1px solid #ccc;
padding: 6px;
}
#main table tr th {
background: #efefef;
color: #888;
font-size: 80%;
text-transform:uppercase;
}
#main table tr td.no-data {
text-align: center;
padding: 40px 0;
color: #999;
font-style: italic;
font-size: 130%;
}
#main a {
color: #111;
}
#main p {
margin: 5px 0;
}
#main p.intro {
margin-bottom: 15px;
font-size: 85%;
color: #999;
margin-top: 0;
line-height: 1.3;
}
#main h1.wi {
margin-bottom: 5px;
}
#main p.sub {
font-size: 95%;
color: #999;
}
.experiment {
background:#fff;
border: 1px solid #eee;
border-bottom:none;
margin:30px 0;
}
.experiment_with_goal {
margin: -32px 0 30px 0;
}
.experiment .experiment-header {
background: #f4f4f4;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#f4f4f4),
color-stop(100%,#e0e0e0));
background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);
background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
border-top:1px solid #fff;
overflow:hidden;
padding:0 10px;
}
.experiment h2 {
color:#888;
margin: 12px 0 12px 0;
font-size: 1em;
font-weight:bold;
float:left;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
}
.experiment h2 .goal {
font-style: italic;
}
.experiment h2 .version {
font-style:italic;
font-size:0.8em;
color:#bbb;
font-weight:normal;
}
.experiment table em{
font-style:italic;
font-size:0.9em;
color:#bbb;
}
.experiment table .totals td {
background: #eee;
font-weight: bold;
}
#footer {
padding: 10px 5%;
color: #999;
font-size: 85%;
line-height: 1.5;
padding-top: 10px;
}
#footer p a {
color: #999;
}
.inline-controls {
float:right;
}
.inline-controls small {
color: #888;
font-size: 11px;
}
.inline-controls form {
display: inline-block;
font-size: 10px;
line-height: 38px;
}
.inline-controls input {
margin-left: 10px;
}
.worse, .better {
color: #773F3F;
font-size: 10px;
font-weight:bold;
}
.better {
color: #408C48;
}
.experiment a.button, .experiment button, .experiment input[type="submit"] {
padding: 4px 10px;
overflow: hidden;
background: #d8dae0;
-moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);
-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);
box-shadow: 0 1px 0 rgba(0,0,0,0.5);
border:none;
-moz-border-radius: 30px;
-webkit-border-radius:30px;
border-radius: 30px;
color:#2e3035;
cursor: pointer;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
text-decoration: none;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
-moz-user-select: none;
-webkit-user-select:none;
user-select: none;
white-space: nowrap;
}
a.button:hover, button:hover, input[type="submit"]:hover,
a.button:focus, button:focus, input[type="submit"]:focus{
background:#bbbfc7;
}
a.button:active, button:active, input[type="submit"]:active{
-moz-box-shadow: inset 0 0 4px #484d57;
-webkit-box-shadow:inset 0 0 4px #484d57;
box-shadow: inset 0 0 4px #484d57;
position:relative;
top:1px;
}
a.button.red, button.red, input[type="submit"].red,
a.button.green, button.green, input[type="submit"].green {
color:#fff;
text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
a.button.red, button.red, input[type="submit"].red {
background:#a56d6d;
}
a.button.red:hover, button.red:hover, input[type="submit"].red:hover,
a.button.red:focus, button.red:focus, input[type="submit"].red:focus {
background:#895C5C;
}
a.button.green, button.green, input[type="submit"].green {
background:#8daa92;
}
a.button.green:hover, button.green:hover, input[type="submit"].green:hover,
a.button.green:focus, button.green:focus, input[type="submit"].green:focus {
background:#768E7A;
}
.dashboard-controls input, .dashboard-controls select {
padding: 10px;
}
.dashboard-controls-bottom {
margin-top: 10px;
}
.pagination {
text-align: center;
font-size: 15px;
}
.pagination a, .paginaton span {
display: inline-block;
padding: 5px;
}
.divider {
display: inline-block;
margin-left: 10px;
}
<MSG> Merge pull request #299 from xicreative/remove-body-max-width
Remove body "max-width" from dashboard.
<DFF> @@ -7,7 +7,6 @@ html {
body {
padding: 0 10px;
margin: 10px auto 0;
- max-width:800px;
}
.header {
| 0 | Merge pull request #299 from xicreative/remove-body-max-width | 1 | .css | css | mit | splitrb/split |
10069320 | <NME> style.css
<BEF> html {
background: #efefef;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 13px;
}
body {
padding: 0 10px;
margin: 10px auto 0;
max-width:800px;
}
.header {
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#576a76),
color-stop(100%,#4d5256));
background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);
background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);
background: linear-gradient(top, #576a76 0%, #414e58 100%);
border-bottom: 1px solid #fff;
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
border-top-left-radius: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius:5px;
border-top-right-radius: 5px;
overflow:hidden;
padding: 10px 5%;
text-shadow:0 1px 0 #000;
}
.header h1 {
color: #eee;
float:left;
font-size:1.2em;
font-weight:normal;
margin:2px 30px 0 0;
}
.header ul li {
display: inline;
}
.header ul li a {
color: #eee;
text-decoration: none;
margin-right: 10px;
display: inline-block;
padding: 4px 8px;
-moz-border-radius: 10px;
-webkit-border-radius:10px;
border-radius: 10px;
}
.header ul li a:hover {
background: rgba(255,255,255,0.1);
}
.header ul li a:active {
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
}
.header ul li.current a {
background: rgba(255,255,255,0.1);
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
color: #fff;
}
.header p.environment {
clear: both;
padding: 10px 0 0 0;
color: #BBB;
font-style: italic;
float: right;
}
#main {
padding: 10px 5%;
background: #f9f9f9;
border:1px solid #ccc;
border-top:none;
-moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);
-webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);
box-shadow: 0 3px 10px rgba(0,0,0,0.2);
overflow: hidden;
}
#main .logo {
float: right;
margin: 10px;
}
#main span.hl {
background: #efefef;
padding: 2px;
}
#main h1 {
margin: 10px 0;
font-size: 190%;
font-weight: bold;
color: #0080FF;
}
#main table {
width: 100%;
margin:0 0 10px;
}
#main table tr td, #main table tr th {
border-bottom: 1px solid #ccc;
padding: 6px;
}
#main table tr th {
background: #efefef;
color: #888;
font-size: 80%;
text-transform:uppercase;
}
#main table tr td.no-data {
text-align: center;
padding: 40px 0;
color: #999;
font-style: italic;
font-size: 130%;
}
#main a {
color: #111;
}
#main p {
margin: 5px 0;
}
#main p.intro {
margin-bottom: 15px;
font-size: 85%;
color: #999;
margin-top: 0;
line-height: 1.3;
}
#main h1.wi {
margin-bottom: 5px;
}
#main p.sub {
font-size: 95%;
color: #999;
}
.experiment {
background:#fff;
border: 1px solid #eee;
border-bottom:none;
margin:30px 0;
}
.experiment_with_goal {
margin: -32px 0 30px 0;
}
.experiment .experiment-header {
background: #f4f4f4;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#f4f4f4),
color-stop(100%,#e0e0e0));
background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);
background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
border-top:1px solid #fff;
overflow:hidden;
padding:0 10px;
}
.experiment h2 {
color:#888;
margin: 12px 0 12px 0;
font-size: 1em;
font-weight:bold;
float:left;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
}
.experiment h2 .goal {
font-style: italic;
}
.experiment h2 .version {
font-style:italic;
font-size:0.8em;
color:#bbb;
font-weight:normal;
}
.experiment table em{
font-style:italic;
font-size:0.9em;
color:#bbb;
}
.experiment table .totals td {
background: #eee;
font-weight: bold;
}
#footer {
padding: 10px 5%;
color: #999;
font-size: 85%;
line-height: 1.5;
padding-top: 10px;
}
#footer p a {
color: #999;
}
.inline-controls {
float:right;
}
.inline-controls small {
color: #888;
font-size: 11px;
}
.inline-controls form {
display: inline-block;
font-size: 10px;
line-height: 38px;
}
.inline-controls input {
margin-left: 10px;
}
.worse, .better {
color: #773F3F;
font-size: 10px;
font-weight:bold;
}
.better {
color: #408C48;
}
.experiment a.button, .experiment button, .experiment input[type="submit"] {
padding: 4px 10px;
overflow: hidden;
background: #d8dae0;
-moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);
-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);
box-shadow: 0 1px 0 rgba(0,0,0,0.5);
border:none;
-moz-border-radius: 30px;
-webkit-border-radius:30px;
border-radius: 30px;
color:#2e3035;
cursor: pointer;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
text-decoration: none;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
-moz-user-select: none;
-webkit-user-select:none;
user-select: none;
white-space: nowrap;
}
a.button:hover, button:hover, input[type="submit"]:hover,
a.button:focus, button:focus, input[type="submit"]:focus{
background:#bbbfc7;
}
a.button:active, button:active, input[type="submit"]:active{
-moz-box-shadow: inset 0 0 4px #484d57;
-webkit-box-shadow:inset 0 0 4px #484d57;
box-shadow: inset 0 0 4px #484d57;
position:relative;
top:1px;
}
a.button.red, button.red, input[type="submit"].red,
a.button.green, button.green, input[type="submit"].green {
color:#fff;
text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
a.button.red, button.red, input[type="submit"].red {
background:#a56d6d;
}
a.button.red:hover, button.red:hover, input[type="submit"].red:hover,
a.button.red:focus, button.red:focus, input[type="submit"].red:focus {
background:#895C5C;
}
a.button.green, button.green, input[type="submit"].green {
background:#8daa92;
}
a.button.green:hover, button.green:hover, input[type="submit"].green:hover,
a.button.green:focus, button.green:focus, input[type="submit"].green:focus {
background:#768E7A;
}
.dashboard-controls input, .dashboard-controls select {
padding: 10px;
}
.dashboard-controls-bottom {
margin-top: 10px;
}
.pagination {
text-align: center;
font-size: 15px;
}
.pagination a, .paginaton span {
display: inline-block;
padding: 5px;
}
.divider {
display: inline-block;
margin-left: 10px;
}
<MSG> Merge pull request #299 from xicreative/remove-body-max-width
Remove body "max-width" from dashboard.
<DFF> @@ -7,7 +7,6 @@ html {
body {
padding: 0 10px;
margin: 10px auto 0;
- max-width:800px;
}
.header {
| 0 | Merge pull request #299 from xicreative/remove-body-max-width | 1 | .css | css | mit | splitrb/split |
10069321 | <NME> style.css
<BEF> html {
background: #efefef;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 13px;
}
body {
padding: 0 10px;
margin: 10px auto 0;
max-width:800px;
}
.header {
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#576a76),
color-stop(100%,#4d5256));
background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);
background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);
background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);
background: linear-gradient(top, #576a76 0%, #414e58 100%);
border-bottom: 1px solid #fff;
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
border-top-left-radius: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius:5px;
border-top-right-radius: 5px;
overflow:hidden;
padding: 10px 5%;
text-shadow:0 1px 0 #000;
}
.header h1 {
color: #eee;
float:left;
font-size:1.2em;
font-weight:normal;
margin:2px 30px 0 0;
}
.header ul li {
display: inline;
}
.header ul li a {
color: #eee;
text-decoration: none;
margin-right: 10px;
display: inline-block;
padding: 4px 8px;
-moz-border-radius: 10px;
-webkit-border-radius:10px;
border-radius: 10px;
}
.header ul li a:hover {
background: rgba(255,255,255,0.1);
}
.header ul li a:active {
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
}
.header ul li.current a {
background: rgba(255,255,255,0.1);
-moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
-webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);
box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);
color: #fff;
}
.header p.environment {
clear: both;
padding: 10px 0 0 0;
color: #BBB;
font-style: italic;
float: right;
}
#main {
padding: 10px 5%;
background: #f9f9f9;
border:1px solid #ccc;
border-top:none;
-moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);
-webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);
box-shadow: 0 3px 10px rgba(0,0,0,0.2);
overflow: hidden;
}
#main .logo {
float: right;
margin: 10px;
}
#main span.hl {
background: #efefef;
padding: 2px;
}
#main h1 {
margin: 10px 0;
font-size: 190%;
font-weight: bold;
color: #0080FF;
}
#main table {
width: 100%;
margin:0 0 10px;
}
#main table tr td, #main table tr th {
border-bottom: 1px solid #ccc;
padding: 6px;
}
#main table tr th {
background: #efefef;
color: #888;
font-size: 80%;
text-transform:uppercase;
}
#main table tr td.no-data {
text-align: center;
padding: 40px 0;
color: #999;
font-style: italic;
font-size: 130%;
}
#main a {
color: #111;
}
#main p {
margin: 5px 0;
}
#main p.intro {
margin-bottom: 15px;
font-size: 85%;
color: #999;
margin-top: 0;
line-height: 1.3;
}
#main h1.wi {
margin-bottom: 5px;
}
#main p.sub {
font-size: 95%;
color: #999;
}
.experiment {
background:#fff;
border: 1px solid #eee;
border-bottom:none;
margin:30px 0;
}
.experiment_with_goal {
margin: -32px 0 30px 0;
}
.experiment .experiment-header {
background: #f4f4f4;
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0%,#f4f4f4),
color-stop(100%,#e0e0e0));
background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);
background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);
border-top:1px solid #fff;
overflow:hidden;
padding:0 10px;
}
.experiment h2 {
color:#888;
margin: 12px 0 12px 0;
font-size: 1em;
font-weight:bold;
float:left;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
}
.experiment h2 .goal {
font-style: italic;
}
.experiment h2 .version {
font-style:italic;
font-size:0.8em;
color:#bbb;
font-weight:normal;
}
.experiment table em{
font-style:italic;
font-size:0.9em;
color:#bbb;
}
.experiment table .totals td {
background: #eee;
font-weight: bold;
}
#footer {
padding: 10px 5%;
color: #999;
font-size: 85%;
line-height: 1.5;
padding-top: 10px;
}
#footer p a {
color: #999;
}
.inline-controls {
float:right;
}
.inline-controls small {
color: #888;
font-size: 11px;
}
.inline-controls form {
display: inline-block;
font-size: 10px;
line-height: 38px;
}
.inline-controls input {
margin-left: 10px;
}
.worse, .better {
color: #773F3F;
font-size: 10px;
font-weight:bold;
}
.better {
color: #408C48;
}
.experiment a.button, .experiment button, .experiment input[type="submit"] {
padding: 4px 10px;
overflow: hidden;
background: #d8dae0;
-moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);
-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);
box-shadow: 0 1px 0 rgba(0,0,0,0.5);
border:none;
-moz-border-radius: 30px;
-webkit-border-radius:30px;
border-radius: 30px;
color:#2e3035;
cursor: pointer;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
text-decoration: none;
text-shadow:0 1px 0 rgba(255,255,255,0.8);
-moz-user-select: none;
-webkit-user-select:none;
user-select: none;
white-space: nowrap;
}
a.button:hover, button:hover, input[type="submit"]:hover,
a.button:focus, button:focus, input[type="submit"]:focus{
background:#bbbfc7;
}
a.button:active, button:active, input[type="submit"]:active{
-moz-box-shadow: inset 0 0 4px #484d57;
-webkit-box-shadow:inset 0 0 4px #484d57;
box-shadow: inset 0 0 4px #484d57;
position:relative;
top:1px;
}
a.button.red, button.red, input[type="submit"].red,
a.button.green, button.green, input[type="submit"].green {
color:#fff;
text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
a.button.red, button.red, input[type="submit"].red {
background:#a56d6d;
}
a.button.red:hover, button.red:hover, input[type="submit"].red:hover,
a.button.red:focus, button.red:focus, input[type="submit"].red:focus {
background:#895C5C;
}
a.button.green, button.green, input[type="submit"].green {
background:#8daa92;
}
a.button.green:hover, button.green:hover, input[type="submit"].green:hover,
a.button.green:focus, button.green:focus, input[type="submit"].green:focus {
background:#768E7A;
}
.dashboard-controls input, .dashboard-controls select {
padding: 10px;
}
.dashboard-controls-bottom {
margin-top: 10px;
}
.pagination {
text-align: center;
font-size: 15px;
}
.pagination a, .paginaton span {
display: inline-block;
padding: 5px;
}
.divider {
display: inline-block;
margin-left: 10px;
}
<MSG> Merge pull request #299 from xicreative/remove-body-max-width
Remove body "max-width" from dashboard.
<DFF> @@ -7,7 +7,6 @@ html {
body {
padding: 0 10px;
margin: 10px auto 0;
- max-width:800px;
}
.header {
| 0 | Merge pull request #299 from xicreative/remove-body-max-width | 1 | .css | css | mit | splitrb/split |
10069322 | <NME> transducers.js
<BEF>
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
throw new Error("don't know how to " + name + " collection: " +
coll);
}
function fulfillsProtocol(obj, name) {
if(name === 'iterator') {
// Accept ill-formed iterators that don't conform to the
// protocol by accepting just next()
return obj[protocols.iterator] || obj.next;
}
return obj[protocols[name]];
}
function getProtocolProperty(obj, name) {
return obj[protocols[name]];
}
function iterator(coll) {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
else if(isObject(coll)) {
return new ObjectIterator(coll);
}
}
function ArrayIterator(arr) {
this.arr = arr;
this.index = 0;
}
ArrayIterator.prototype.next = function() {
if(this.index < this.arr.length) {
return {
value: this.arr[this.index++],
done: false
};
}
return {
done: true
}
};
function ObjectIterator(obj) {
this.obj = obj;
this.keys = Object.keys(obj);
this.index = 0;
}
ObjectIterator.prototype.next = function() {
if(this.index < this.keys.length) {
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
}
function isNumber(x) {
return typeof x === 'number';
}
function Reduced(value) {
this['@@transducer/reduced'] = true;
this['@@transducer/value'] = value;
}
function Reduced(value) {
this.__transducers_reduced__ = true;
this.value = value;
return val;
} else {
return new Reduced(val);
}
}
/**
* This is for tranforms that call their nested transforms when
* performing completion (like "partition"), to avoid signaling
* termination after already completing.
*/
function ensureUnreduced(v) {
if(isReduced(v)) {
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform['@@transducer/step'](result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform['@@transducer/result'](result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform.step(result, coll[index]);
return value;
}
}
// transformations
function transformer(f) {
var t = {};
t['@@transducer/init'] = function() {
throw new Error('init value unavailable');
};
t['@@transducer/result'] = function(v) {
return v;
};
t['@@transducer/step'] = f;
return t;
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
init = xform.init();
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
function arrayMap(arr, f, ctx) {
var index = -1;
var length = arr.length;
var result = Array(length);
f = bound(f, ctx, 2);
// transformations
function transformer(f) {
return {
init: function() {
throw new Error('init value unavailable');
},
result: function(v) {
return v;
},
step: f
}
return result;
}
function Map(f, xform) {
this.xform = xform;
this.f = f;
}
Map.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Map.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Map.prototype['@@transducer/step'] = function(res, input) {
return this.xform['@@transducer/step'](res, this.f(input));
};
function map(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(coll, f, ctx);
}
return seq(coll, map(f));
}
return function(xform) {
return new Map(f, xform);
}
}
function Filter(f, xform) {
this.xform = xform;
this.f = f;
}
Filter.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Filter.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Filter.prototype['@@transducer/step'] = function(res, input) {
if(this.f(input)) {
this.f = f;
}
Map.prototype.init = function() {
return this.xform.init();
return function(xform) {
return new Filter(f, xform);
};
}
function remove(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
return filter(coll, function(x) { return !f(x); });
}
function keep(coll) {
return filter(coll, function(x) { return x != null });
}
function Dedupe(xform) {
this.xform = xform;
this.last = undefined;
}
Dedupe.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Dedupe.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
this.f = f;
}
Filter.prototype.init = function() {
return this.xform.init();
function TakeWhile(f, xform) {
this.xform = xform;
this.f = f;
}
TakeWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.f(input)) {
return this.xform['@@transducer/step'](result, input);
}
return new Reduced(result);
};
function takeWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, takeWhile(f));
}
return function(xform) {
return new TakeWhile(f, xform);
}
}
function Take(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Take.prototype['@@transducer/init'] = function() {
this.last = undefined;
}
Dedupe.prototype.init = function() {
return this.xform.init();
};
function take(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, take(n));
}
return function(xform) {
return new Take(n, xform);
}
}
function Drop(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Drop.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Drop.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
this.f = f;
}
TakeWhile.prototype.init = function() {
return this.xform.init();
return new Drop(n, xform);
}
}
function DropWhile(f, xform) {
this.xform = xform;
this.f = f;
this.dropping = true;
}
DropWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
DropWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
DropWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
}
else {
this.dropping = false;
}
}
return this.xform['@@transducer/step'](result, input);
};
this.xform = xform;
}
Take.prototype.init = function() {
return this.xform.init();
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Partition.prototype['@@transducer/result'] = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));
}
return this.xform['@@transducer/result'](v);
};
Partition.prototype['@@transducer/step'] = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform['@@transducer/step'](result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
this.xform = xform;
}
Drop.prototype.init = function() {
return this.xform.init();
return this.xform['@@transducer/init']();
};
PartitionBy.prototype['@@transducer/result'] = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l)));
}
return this.xform['@@transducer/result'](v);
};
PartitionBy.prototype['@@transducer/step'] = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform['@@transducer/step'](result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
this.dropping = true;
}
DropWhile.prototype.init = function() {
return this.xform.init();
return this.xform['@@transducer/init']();
};
Interpose.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Interpose.prototype['@@transducer/step'] = function(result, input) {
if (this.started) {
var withSep = this.xform['@@transducer/step'](result, this.sep);
if (isReduced(withSep)) {
return withSep;
this.dropping = false;
}
}
return this.xform.step(result, input);
};
/**
* Returns a new collection containing elements of the given
* collection, separated by the specified separator. Returns a
* transducer if a collection is not provided.
*/
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
function Repeat(n, xform) {
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype.init = function() {
return this.xform.init();
* collection, each repeated n times. Returns a transducer if a
* collection is not provided.
*/
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
function TakeNth(n, xform) {
this.xform = xform;
this.n = n;
this.i = -1;
}
TakeNth.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeNth.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeNth.prototype['@@transducer/step'] = function(result, input) {
this.i += 1;
if (this.i % this.n === 0) {
return this.xform['@@transducer/step'](result, input);
}
return result;
};
/**
* Returns a new collection of every nth element of the given
* collection. Returns a transducer if a collection is not provided.
*/
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
this.last = NOTHING;
}
PartitionBy.prototype.init = function() {
return this.xform.init();
return xform['@@transducer/init']();
};
newxform['@@transducer/result'] = function(v) {
return v;
};
newxform['@@transducer/step'] = function(result, input) {
var val = xform['@@transducer/step'](result, input);
return isReduced(val) ? deref(val) : val;
};
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
else {
var keys = Object.keys(x);
var len = keys.length;
for(var i=0; i<len; i++) {
obj[keys[i]] = x[keys[i]];
this.xform = xform;
}
Cat.prototype.init = function() {
return this.xform.init();
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(coll['@@transducer/step']) {
var init;
if(coll['@@transducer/init']) {
init = coll['@@transducer/init']();
}
else {
init = new coll.constructor();
}
return transduce(coll, xform, coll, init);
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(to['@@transducer/step']) {
return obj;
}
var arrayReducer = {
init: function() {
return [];
},
result: function(v) {
return v;
},
step: push
}
Stepper.prototype['@@transducer/step'] = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform['@@transducer/result'](this);
break;
}
// step
this.xform['@@transducer/step'](lt, n.value);
}
}
else if(isObject(coll)) {
return objReducer;
}
else if(fulfillsProtocol(coll, 'transformer')) {
return getProtocolProperty(coll, 'transformer');
return this;
}
LazyTransformer.prototype.next = function() {
this['@@transducer/step']();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype['@@transducer/step'] = function() {
if(!this.items.length) {
this.stepper['@@transducer/step'](this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(fulfillsProtocol(coll, 'transformer')) {
var transformer = getProtocolProperty(coll, 'transformer');
return transduce(coll, xform, transformer, transformer.init());
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
takeNth: takeNth,
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(fulfillsProtocol(to, 'transformer')) {
// laziness
var stepper = {
result: function(v) {
return isReduced(v) ? deref(v) : v;
},
step: function(lt, x) {
lt.items.push(x);
return lt.rest;
}
}
}
LazyTransformer.prototype.next = function() {
this.step();
}
};
LazyTransformer.prototype.step = function() {
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
partitionBy: partitionBy,
range: range,
protocols: protocols,
LazyTransformer: LazyTransformer
};
<MSG> update to conform to the new transducer protocol
<DFF> @@ -4,8 +4,7 @@
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
- iterator: symbolExists ? Symbol.iterator : '@@iterator',
- transformer: symbolExists ? Symbol('transformer') : '@@transformer'
+ iterator: symbolExists ? Symbol.iterator : '@@iterator'
};
function throwProtocolError(name, coll) {
@@ -104,16 +103,16 @@ function isNumber(x) {
}
function Reduced(value) {
- this.__transducers_reduced__ = true;
- this.value = value;
+ this['@@transducer/reduced'] = true;
+ this['@@transducer/value'] = value;
}
function isReduced(x) {
- return (x instanceof Reduced) || (x && x.__transducers_reduced__);
+ return (x instanceof Reduced) || (x && x['@@transducer/reduced']);
}
function deref(x) {
- return x.value;
+ return x['@@transducer/value'];
}
/**
@@ -147,27 +146,27 @@ function reduce(coll, xform, init) {
var index = -1;
var len = coll.length;
while(++index < len) {
- result = xform.step(result, coll[index]);
+ result = xform['@@transducer/step'](result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
- return xform.result(result);
+ return xform['@@transducer/result'](result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
- result = xform.step(result, val.value);
+ result = xform['@@transducer/step'](result, val.value);
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
- return xform.result(result);
+ return xform['@@transducer/result'](result);
}
throwProtocolError('iterate', coll);
}
@@ -175,7 +174,7 @@ function reduce(coll, xform, init) {
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
- init = xform.init();
+ init = xform['@@transducer/init']();
}
return reduce(coll, xform, init);
}
@@ -194,15 +193,15 @@ function compose() {
// transformations
function transformer(f) {
- return {
- init: function() {
- throw new Error('init value unavailable');
- },
- result: function(v) {
- return v;
- },
- step: f
+ var t = {};
+ t['@@transducer/init'] = function() {
+ throw new Error('init value unavailable');
+ };
+ t['@@transducer/result'] = function(v) {
+ return v;
};
+ t['@@transducer/step'] = f;
+ return t;
}
function bound(f, ctx, count) {
@@ -257,16 +256,16 @@ function Map(f, xform) {
this.f = f;
}
-Map.prototype.init = function() {
- return this.xform.init();
+Map.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Map.prototype.result = function(v) {
- return this.xform.result(v);
+Map.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Map.prototype.step = function(res, input) {
- return this.xform.step(res, this.f(input));
+Map.prototype['@@transducer/step'] = function(res, input) {
+ return this.xform['@@transducer/step'](res, this.f(input));
};
function map(coll, f, ctx) {
@@ -290,17 +289,17 @@ function Filter(f, xform) {
this.f = f;
}
-Filter.prototype.init = function() {
- return this.xform.init();
+Filter.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Filter.prototype.result = function(v) {
- return this.xform.result(v);
+Filter.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Filter.prototype.step = function(res, input) {
+Filter.prototype['@@transducer/step'] = function(res, input) {
if(this.f(input)) {
- return this.xform.step(res, input);
+ return this.xform['@@transducer/step'](res, input);
}
return res;
};
@@ -336,18 +335,18 @@ function Dedupe(xform) {
this.last = undefined;
}
-Dedupe.prototype.init = function() {
- return this.xform.init();
+Dedupe.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Dedupe.prototype.result = function(v) {
- return this.xform.result(v);
+Dedupe.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Dedupe.prototype.step = function(result, input) {
+Dedupe.prototype['@@transducer/step'] = function(result, input) {
if(input !== this.last) {
this.last = input;
- return this.xform.step(result, input);
+ return this.xform['@@transducer/step'](result, input);
}
return result;
};
@@ -367,17 +366,17 @@ function TakeWhile(f, xform) {
this.f = f;
}
-TakeWhile.prototype.init = function() {
- return this.xform.init();
+TakeWhile.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-TakeWhile.prototype.result = function(v) {
- return this.xform.result(v);
+TakeWhile.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-TakeWhile.prototype.step = function(result, input) {
+TakeWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.f(input)) {
- return this.xform.step(result, input);
+ return this.xform['@@transducer/step'](result, input);
}
return new Reduced(result);
};
@@ -401,17 +400,17 @@ function Take(n, xform) {
this.xform = xform;
}
-Take.prototype.init = function() {
- return this.xform.init();
+Take.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Take.prototype.result = function(v) {
- return this.xform.result(v);
+Take.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Take.prototype.step = function(result, input) {
+Take.prototype['@@transducer/step'] = function(result, input) {
if (this.i < this.n) {
- result = this.xform.step(result, input);
+ result = this.xform['@@transducer/step'](result, input);
if(this.i + 1 >= this.n) {
// Finish reducing on the same step as the final value. TODO:
// double-check that this doesn't break any semantics
@@ -440,19 +439,19 @@ function Drop(n, xform) {
this.xform = xform;
}
-Drop.prototype.init = function() {
- return this.xform.init();
+Drop.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Drop.prototype.result = function(v) {
- return this.xform.result(v);
+Drop.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Drop.prototype.step = function(result, input) {
+Drop.prototype['@@transducer/step'] = function(result, input) {
if(this.i++ < this.n) {
return result;
}
- return this.xform.step(result, input);
+ return this.xform['@@transducer/step'](result, input);
};
function drop(coll, n) {
@@ -473,15 +472,15 @@ function DropWhile(f, xform) {
this.dropping = true;
}
-DropWhile.prototype.init = function() {
- return this.xform.init();
+DropWhile.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-DropWhile.prototype.result = function(v) {
- return this.xform.result(v);
+DropWhile.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-DropWhile.prototype.step = function(result, input) {
+DropWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
@@ -490,7 +489,7 @@ DropWhile.prototype.step = function(result, input) {
this.dropping = false;
}
}
- return this.xform.step(result, input);
+ return this.xform['@@transducer/step'](result, input);
};
function dropWhile(coll, f, ctx) {
@@ -513,25 +512,25 @@ function Partition(n, xform) {
this.part = new Array(n);
}
-Partition.prototype.init = function() {
- return this.xform.init();
+Partition.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Partition.prototype.result = function(v) {
+Partition.prototype['@@transducer/result'] = function(v) {
if (this.i > 0) {
- return ensureUnreduced(this.xform.step(v, this.part.slice(0, this.i)));
+ return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));
}
- return this.xform.result(v);
+ return this.xform['@@transducer/result'](v);
};
-Partition.prototype.step = function(result, input) {
+Partition.prototype['@@transducer/step'] = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
- return this.xform.step(result, out);
+ return this.xform['@@transducer/step'](result, out);
}
return result;
};
@@ -561,24 +560,24 @@ function PartitionBy(f, xform) {
this.last = NOTHING;
}
-PartitionBy.prototype.init = function() {
- return this.xform.init();
+PartitionBy.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-PartitionBy.prototype.result = function(v) {
+PartitionBy.prototype['@@transducer/result'] = function(v) {
var l = this.part.length;
if (l > 0) {
- return ensureUnreduced(this.xform.step(v, this.part.slice(0, l)));
+ return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l)));
}
- return this.xform.result(v);
+ return this.xform['@@transducer/result'](v);
};
-PartitionBy.prototype.step = function(result, input) {
+PartitionBy.prototype['@@transducer/step'] = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
- result = this.xform.step(result, this.part);
+ result = this.xform['@@transducer/step'](result, this.part);
this.part = [input];
}
this.last = current;
@@ -604,28 +603,27 @@ function Cat(xform) {
this.xform = xform;
}
-Cat.prototype.init = function() {
- return this.xform.init();
+Cat.prototype['@@transducer/init'] = function() {
+ return this.xform['@@transducer/init']();
};
-Cat.prototype.result = function(v) {
- return this.xform.result(v);
+Cat.prototype['@@transducer/result'] = function(v) {
+ return this.xform['@@transducer/result'](v);
};
-Cat.prototype.step = function(result, input) {
+Cat.prototype['@@transducer/step'] = function(result, input) {
var xform = this.xform;
- var newxform = {
- init: function() {
- return xform.init();
- },
- result: function(v) {
- return v;
- },
- step: function(result, input) {
- var val = xform.step(result, input);
- return isReduced(val) ? deref(val) : val;
- }
- }
+ var newxform = {};
+ newxform['@@transducer/init'] = function() {
+ return xform['@@transducer/init']();
+ };
+ newxform['@@transducer/result'] = function(v) {
+ return v;
+ };
+ newxform['@@transducer/step'] = function(result, input) {
+ var val = xform['@@transducer/step'](result, input);
+ return isReduced(val) ? deref(val) : val;
+ };
return reduce(input, newxform, result);
};
@@ -660,25 +658,23 @@ function merge(obj, x) {
return obj;
}
-var arrayReducer = {
- init: function() {
- return [];
- },
- result: function(v) {
- return v;
- },
- step: push
-}
+var arrayReducer = {};
+arrayReducer['@@transducer/init'] = function() {
+ return [];
+};
+arrayReducer['@@transducer/result'] = function(v) {
+ return v;
+};
+arrayReducer['@@transducer/step'] = push;
-var objReducer = {
- init: function() {
- return {};
- },
- result: function(v) {
- return v;
- },
- step: merge
+var objReducer = {};
+objReducer['@@transducer/init'] = function() {
+ return {};
+};
+objReducer['@@transducer/result'] = function(v) {
+ return v;
};
+objReducer['@@transducer/step'] = merge;
function getReducer(coll) {
if(isArray(coll)) {
@@ -687,8 +683,8 @@ function getReducer(coll) {
else if(isObject(coll)) {
return objReducer;
}
- else if(fulfillsProtocol(coll, 'transformer')) {
- return getProtocolProperty(coll, 'transformer');
+ else if(coll['@@transducer/step']) {
+ return coll;
}
throwProtocolError('getReducer', coll);
}
@@ -723,9 +719,16 @@ function seq(coll, xform) {
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
- else if(fulfillsProtocol(coll, 'transformer')) {
- var transformer = getProtocolProperty(coll, 'transformer');
- return transduce(coll, xform, transformer, transformer.init());
+ else if(coll['@@transducer/step']) {
+ var init;
+ if(coll['@@transducer/init']) {
+ init = coll['@@transducer/init']();
+ }
+ else {
+ init = new coll.constructor();
+ }
+
+ return transduce(coll, xform, coll, init);
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
@@ -740,10 +743,10 @@ function into(to, xform, from) {
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
- else if(fulfillsProtocol(to, 'transformer')) {
+ else if(to['@@transducer/step']) {
return transduce(from,
xform,
- getProtocolProperty(to, 'transformer'),
+ to,
to);
}
throwProtocolError('into', to);
@@ -751,33 +754,32 @@ function into(to, xform, from) {
// laziness
-var stepper = {
- result: function(v) {
- return isReduced(v) ? deref(v) : v;
- },
- step: function(lt, x) {
- lt.items.push(x);
- return lt.rest;
- }
-}
+var stepper = {};
+stepper['@@transducer/result'] = function(v) {
+ return isReduced(v) ? deref(v) : v;
+};
+stepper['@@transducer/step'] = function(lt, x) {
+ lt.items.push(x);
+ return lt.rest;
+};
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
-Stepper.prototype.step = function(lt) {
+Stepper.prototype['@@transducer/step'] = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
- this.xform.result(this);
+ this.xform['@@transducer/result'](this);
break;
}
// step
- this.xform.step(lt, n.value);
+ this.xform['@@transducer/step'](lt, n.value);
}
}
@@ -792,7 +794,7 @@ LazyTransformer.prototype[protocols.iterator] = function() {
}
LazyTransformer.prototype.next = function() {
- this.step();
+ this['@@transducer/step']();
if(this.items.length) {
return {
@@ -805,9 +807,9 @@ LazyTransformer.prototype.next = function() {
}
};
-LazyTransformer.prototype.step = function() {
+LazyTransformer.prototype['@@transducer/step'] = function() {
if(!this.items.length) {
- this.stepper.step(this);
+ this.stepper['@@transducer/step'](this);
}
}
@@ -821,7 +823,6 @@ function range(n) {
return arr;
}
-
module.exports = {
reduce: reduce,
transformer: transformer,
@@ -851,6 +852,5 @@ module.exports = {
partitionBy: partitionBy,
range: range,
- protocols: protocols,
LazyTransformer: LazyTransformer
};
| 133 | update to conform to the new transducer protocol | 133 | .js | js | bsd-2-clause | jlongster/transducers.js |
10069323 | <NME> helper.rb
<BEF> module Split
module Helper
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
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)
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)
return experiment_pairs
end
protected
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
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> Merge pull request #303 from ipoval/private-methods-in-controllers
[private-methods-in-controllers] prevents split helper-methods to become...
<DFF> @@ -1,5 +1,6 @@
module Split
module Helper
+ module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
@@ -129,8 +130,6 @@ module Split
return experiment_pairs
end
- protected
-
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
| 1 | Merge pull request #303 from ipoval/private-methods-in-controllers | 2 | .rb | rb | mit | splitrb/split |
10069324 | <NME> helper.rb
<BEF> module Split
module Helper
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
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)
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)
return experiment_pairs
end
protected
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
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> Merge pull request #303 from ipoval/private-methods-in-controllers
[private-methods-in-controllers] prevents split helper-methods to become...
<DFF> @@ -1,5 +1,6 @@
module Split
module Helper
+ module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
@@ -129,8 +130,6 @@ module Split
return experiment_pairs
end
- protected
-
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
| 1 | Merge pull request #303 from ipoval/private-methods-in-controllers | 2 | .rb | rb | mit | splitrb/split |
10069325 | <NME> helper.rb
<BEF> module Split
module Helper
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
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)
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)
return experiment_pairs
end
protected
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
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> Merge pull request #303 from ipoval/private-methods-in-controllers
[private-methods-in-controllers] prevents split helper-methods to become...
<DFF> @@ -1,5 +1,6 @@
module Split
module Helper
+ module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
@@ -129,8 +130,6 @@ module Split
return experiment_pairs
end
- protected
-
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
| 1 | Merge pull request #303 from ipoval/private-methods-in-controllers | 2 | .rb | rb | mit | splitrb/split |
10069326 | <NME> trial_spec.rb
<BEF> 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
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
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> Enable frozen_string_literal magic comment
<DFF> @@ -1,3 +1,4 @@
+# frozen_string_literal: true
require 'spec_helper'
require 'split/trial'
| 1 | Enable frozen_string_literal magic comment | 0 | .rb | rb | mit | splitrb/split |
10069327 | <NME> trial_spec.rb
<BEF> 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
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
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> Enable frozen_string_literal magic comment
<DFF> @@ -1,3 +1,4 @@
+# frozen_string_literal: true
require 'spec_helper'
require 'split/trial'
| 1 | Enable frozen_string_literal magic comment | 0 | .rb | rb | mit | splitrb/split |
10069328 | <NME> trial_spec.rb
<BEF> 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
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
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> Enable frozen_string_literal magic comment
<DFF> @@ -1,3 +1,4 @@
+# frozen_string_literal: true
require 'spec_helper'
require 'split/trial'
| 1 | Enable frozen_string_literal magic comment | 0 | .rb | rb | mit | splitrb/split |
10069329 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
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

## 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
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
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> Update README.md
<DFF> @@ -11,6 +11,81 @@ Split is designed to be hacker friendly, allowing for maximum customisation and
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
+
+
+# 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>
+
+
+
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
| 75 | Update README.md | 0 | .md | md | mit | splitrb/split |
10069330 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
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

## 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
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
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> Update README.md
<DFF> @@ -11,6 +11,81 @@ Split is designed to be hacker friendly, allowing for maximum customisation and
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
+
+
+# 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>
+
+
+
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
| 75 | Update README.md | 0 | .md | md | mit | splitrb/split |
10069331 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
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

## 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
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
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> Update README.md
<DFF> @@ -11,6 +11,81 @@ Split is designed to be hacker friendly, allowing for maximum customisation and
[](https://codeclimate.com/github/splitrb/split)
[](https://coveralls.io/r/splitrb/split)
+
+
+# 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>
+
+
+
## Requirements
Split currently requires Ruby 1.9.2 or higher. If your project requires compatibility with Ruby 1.8.x and Rails 2.3, please use v0.8.0.
| 75 | Update README.md | 0 | .md | md | mit | splitrb/split |
10069332 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Removed rails specific code from dashboard
Doesn't work outside of rails
<DFF> @@ -11,7 +11,6 @@
<body>
<div class="header">
<h1>Split Dashboard</h1>
- <p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
| 0 | Removed rails specific code from dashboard | 1 | .erb | erb | mit | splitrb/split |
10069333 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Removed rails specific code from dashboard
Doesn't work outside of rails
<DFF> @@ -11,7 +11,6 @@
<body>
<div class="header">
<h1>Split Dashboard</h1>
- <p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
| 0 | Removed rails specific code from dashboard | 1 | .erb | erb | mit | splitrb/split |
10069334 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Removed rails specific code from dashboard
Doesn't work outside of rails
<DFF> @@ -11,7 +11,6 @@
<body>
<div class="header">
<h1>Split Dashboard</h1>
- <p class="environment"><%= Rails.env.titlecase %></p>
</div>
<div id="main">
| 0 | Removed rails specific code from dashboard | 1 | .erb | erb | mit | splitrb/split |
10069335 | <NME> transducers.js
<BEF> var transducers =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
iterator: symbolExists ? Symbol.iterator : '@@iterator',
transformer: symbolExists ? Symbol('transformer') : '@@transformer'
};
function throwProtocolError(name, coll) {
var names = Array.prototype.slice.call(arguments, 1);
return names.reduce(function(result, name) {
if(symbolExists) {
return result && obj[name === 'iterator' ?
Symbol.iterator :
Symbol.for(name)];
}
else {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return arr;
}
// TODO: get rid of iterate and allow reducers to stop reducing.
// Didn't do that yet because performance.
function Iterated(val) {
this.val = val;
}
function iterate(coll, f) {
if(isArray(coll)) {
for(var i=0; i<coll.length; i++) {
var val = f(coll[i], i);
if(val instanceof Iterated) {
return val.val;
}
}
return;
}
else if(isObject(coll)) {
return iterate(Object.keys(coll), function(k) {
return f([k, coll[k]]);
});
}
else if(fullfillsProtocols(coll, 'iterator')) {
var iter = getProtocolMethod(coll, 'iterator').call(coll);
var val = iter.next();
while(!val.done) {
if(f(val.value) instanceof Iterated) {
return val.value.val;
}
val = iter.next();
}
return;
}
throwProtocolError('iterate', coll);
}
function reduce(coll, f, init) {
if(isArray(coll)) {
var result = init;
this.value = value;
var len = coll.length;
while(++index < len) {
result = f(result, coll[index], index);
}
return result;
}
else if(isObject(coll)) {
return reduce(Object.keys(coll), function(result, k) {
return f(result, [k, coll[k]]);
}, init);
}
else if(fullfillsProtocols(coll, 'iterator')) {
var result = init;
var iter = getProtocolMethod(coll, 'iterator').call(coll);
var val = iter.next();
while(!val.done) {
result = f(result, val.value);
val = iter.next();
}
return result;
}
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform.step(result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform.result(result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
result = xform.step(result, val.value);
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
return xform.result(result);
}
throwProtocolError('iterate', coll);
}
function transduce(coll, xform, reducer, init) {
throwProtocolError('make empty', coll);
}
function transduce(coll, xform, f, init) {
return reduce(coll, xform(f), init);
}
function into(to, xform, from) {
return transduce(from, xform, append, to);
}
function compose() {
}
// transformations
function transformer(f) {
return {
init: function() {
throw new Error('init value unavailable');
},
result: function(v) {
return v;
},
function map(f, coll) {
if(coll) {
if(isArray(coll)) {
return coll.map(f);
}
else {
var i = 0;
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
return function(r) {
var i = 0;
return function(res, input) {
if(input === undefined) {
return r(res, input);
}
return r(res, f(input, i++));
}
}
function arrayMap(arr, f, ctx) {
function filter(f, coll) {
if(coll) {
if(isArray(coll)) {
return coll.filter(f);
}
else {
var i = 0;
return reduce(coll, function(result, x) {
if(f(x, i++)) {
return append(result, x);
}
return result;
}, empty(coll));
return result;
}
function Map(f, xform) {
this.xform = xform;
this.f = f;
}
Map.prototype.init = function() {
return this.xform.init();
};
Map.prototype.result = function(v) {
return this.xform.result(v);
};
return filter(function(x) { return !f(x); }, coll);
}
// function takeWhile(f, coll) {
// if(coll) {
// reduce(coll, function(result, x) {
// if(x) {
// return append(result, x);
// }
// return REDUCE_STOP;
// }, empty(coll));
// }
// }
function keep(f, coll) {
return filter(function(x) { return x != null }, coll);
}
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(coll) {
return reduce(
coll,
function(result, x) {
if(x !== last) {
last = x;
return append(result, x);
}
return result;
},
function Filter(f, xform) {
}
return function(r) {
return function(result, x) {
if(x !== last) {
last = x;
r(result, x);
}
return result;
};
}
}
function take(coll, n) {
if(isNumber(n)) {
var result = empty(coll);
return iterate(coll, function(x, i) {
if(i + 1 <= n) {
result = append(result, x);
}
else {
return Iterated(result);
}
});
}
else {
n = coll;
}
}
// pure transducers (doesn't take collections)
function drop(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, drop(n));
}
return function(xform) {
return new Drop(n, xform);
}
module.exports = {
reduce: reduce,
iterate: iterate,
append: append,
empty: empty,
transduce: transduce,
into: into,
compose: compose,
map: map,
DropWhile.prototype.result = function(v) {
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe
};
}
return this.xform.step(result, input);
};
function dropWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, dropWhile(f));
}
return function(xform) {
return new DropWhile(f, xform);
}
}
function Partition(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype.init = function() {
return this.xform.init();
};
Partition.prototype.result = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform.step(v, this.part.slice(0, this.i)));
}
return this.xform.result(v);
};
Partition.prototype.step = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform.step(result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
}
return function(xform) {
return new Partition(n, xform);
};
}
var NOTHING = {};
function PartitionBy(f, xform) {
// TODO: take an "opts" object that allows the user to specify
// equality
this.f = f;
this.xform = xform;
this.part = [];
this.last = NOTHING;
}
PartitionBy.prototype.init = function() {
return this.xform.init();
};
PartitionBy.prototype.result = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform.step(v, this.part.slice(0, l)));
}
return this.xform.result(v);
};
PartitionBy.prototype.step = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform.step(result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
return seq(coll, partitionBy(f));
}
return function(xform) {
return new PartitionBy(f, xform);
};
}
// pure transducers (cannot take collections)
function Cat(xform) {
this.xform = xform;
}
Cat.prototype.init = function() {
return this.xform.init();
};
Cat.prototype.result = function(v) {
return this.xform.result(v);
};
Cat.prototype.step = function(result, input) {
var xform = this.xform;
var newxform = {
init: function() {
return xform.init();
},
result: function(v) {
return v;
},
step: function(result, input) {
var val = xform.step(result, input);
return isReduced(val) ? deref(val) : val;
}
}
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
else {
var keys = Object.keys(x);
var len = keys.length;
for(var i=0; i<len; i++) {
obj[keys[i]] = x[keys[i]];
}
}
return obj;
}
var arrayReducer = {
init: function() {
return [];
},
result: function(v) {
return v;
},
step: push
}
var objReducer = {
init: function() {
return {};
},
result: function(v) {
return v;
},
step: merge
};
function getReducer(coll) {
if(isArray(coll)) {
return arrayReducer;
}
else if(isObject(coll)) {
return objReducer;
}
else if(fulfillsProtocol(coll, 'transformer')) {
return getProtocolProperty(coll, 'transformer');
}
throwProtocolError('getReducer', coll);
}
// building new collections
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(fulfillsProtocol(coll, 'transformer')) {
var transformer = getProtocolProperty(coll, 'transformer');
return transduce(coll, xform, transformer, transformer.init());
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(fulfillsProtocol(to, 'transformer')) {
return transduce(from,
xform,
getProtocolProperty(to, 'transformer'),
to);
}
throwProtocolError('into', to);
}
// laziness
var stepper = {
result: function(v) {
return isReduced(v) ? deref(v) : v;
},
step: function(lt, x) {
lt.items.push(x);
return lt.rest;
}
}
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
Stepper.prototype.step = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform.result(this);
break;
}
// step
this.xform.step(lt, n.value);
}
}
function LazyTransformer(xform, coll) {
this.iter = iterator(coll);
this.items = [];
this.stepper = new Stepper(xform, iterator(coll));
}
LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
LazyTransformer.prototype.next = function() {
this.step();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype.step = function() {
if(!this.items.length) {
this.stepper.step(this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
Reduced: Reduced,
iterator: iterator,
push: push,
merge: merge,
transduce: transduce,
seq: seq,
toArray: toArray,
toObj: toObj,
toIter: toIter,
into: into,
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
range: range,
protocols: protocols,
LazyTransformer: LazyTransformer
};
/***/ }
/******/ ])
<MSG> rebuild browser
<DFF> @@ -59,11 +59,19 @@ var transducers =
var names = Array.prototype.slice.call(arguments, 1);
return names.reduce(function(result, name) {
if(symbolExists) {
- return result && obj[name === 'iterator' ?
- Symbol.iterator :
- Symbol.for(name)];
+ if(name === 'iterator') {
+ // Accept ill-formed iterators that don'y conform to the
+ // protocol by accepting just next()
+ return result && (obj[Symbol.iterator] || obj.next);
+ }
+ return result && obj[Symbol.for(name)];
}
else {
+ if(name === 'iterator') {
+ // Accept ill-formed iterators that don't conform to the
+ // protocol by accepting just next()
+ return result && (obj['@@iterator'] || obj.next);
+ }
return result && obj['@@' + name];
}
}, true);
@@ -81,12 +89,30 @@ var transducers =
return obj['@@' + name];
}
+ function iterator(coll) {
+ var iter = getProtocolMethod(coll, 'iterator');
+ if(iter) {
+ return iter.call(coll);
+ }
+ else if(coll.next) {
+ // Basic duck typing to except an ill-formed iterator that doesn't
+ // conform to the iterator protocol (all iterators should have the
+ // @@iterator method and return themselves, but some engines don't
+ // have that on generators like older v8)
+ return coll;
+ }
+ }
+
// helpers
function isArray(x) {
return x instanceof Array;
}
+ function isFunction(x) {
+ typeof x === 'function';
+ }
+
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
@@ -104,41 +130,10 @@ var transducers =
return arr;
}
- // TODO: get rid of iterate and allow reducers to stop reducing.
- // Didn't do that yet because performance.
- function Iterated(val) {
+ function Reduced(val) {
this.val = val;
}
- function iterate(coll, f) {
- if(isArray(coll)) {
- for(var i=0; i<coll.length; i++) {
- var val = f(coll[i], i);
- if(val instanceof Iterated) {
- return val.val;
- }
- }
- return;
- }
- else if(isObject(coll)) {
- return iterate(Object.keys(coll), function(k) {
- return f([k, coll[k]]);
- });
- }
- else if(fullfillsProtocols(coll, 'iterator')) {
- var iter = getProtocolMethod(coll, 'iterator').call(coll);
- var val = iter.next();
- while(!val.done) {
- if(f(val.value) instanceof Iterated) {
- return val.value.val;
- }
- val = iter.next();
- }
- return;
- }
- throwProtocolError('iterate', coll);
- }
-
function reduce(coll, f, init) {
if(isArray(coll)) {
var result = init;
@@ -146,21 +141,29 @@ var transducers =
var len = coll.length;
while(++index < len) {
result = f(result, coll[index], index);
+ if(result instanceof Reduced) {
+ return result.val;
+ }
}
return result;
}
else if(isObject(coll)) {
- return reduce(Object.keys(coll), function(result, k) {
- return f(result, [k, coll[k]]);
+ return reduce(Object.keys(coll), function(result, k, i) {
+ return f(result, [k, coll[k]], i);
}, init);
}
else if(fullfillsProtocols(coll, 'iterator')) {
var result = init;
- var iter = getProtocolMethod(coll, 'iterator').call(coll);
+ var iter = iterator(coll);
var val = iter.next();
+ var i = 0;
while(!val.done) {
- result = f(result, val.value);
+ result = f(result, val.value, i);
+ if(result instanceof Reduced) {
+ return result.val;
+ }
val = iter.next();
+ i++;
}
return result;
}
@@ -205,12 +208,16 @@ var transducers =
throwProtocolError('make empty', coll);
}
- function transduce(coll, xform, f, init) {
+ function sequence(xform, coll) {
+ return transduce(xform, append, empty(coll), coll);
+ }
+
+ function transduce(xform, f, init, coll) {
return reduce(coll, xform(f), init);
}
function into(to, xform, from) {
- return transduce(from, xform, append, to);
+ return transduce(xform, append, to, from);
}
function compose() {
@@ -229,7 +236,13 @@ var transducers =
function map(f, coll) {
if(coll) {
if(isArray(coll)) {
- return coll.map(f);
+ var result = [];
+ var index = -1;
+ var len = coll.length;
+ while(++index < len) {
+ result.push(f(coll[index], index));
+ }
+ return result;
}
else {
var i = 0;
@@ -242,9 +255,6 @@ var transducers =
return function(r) {
var i = 0;
return function(res, input) {
- if(input === undefined) {
- return r(res, input);
- }
return r(res, f(input, i++));
}
}
@@ -253,13 +263,21 @@ var transducers =
function filter(f, coll) {
if(coll) {
if(isArray(coll)) {
- return coll.filter(f);
+ var result = [];
+ var index = -1;
+ var len = coll.length;
+ while(++index < len) {
+ if(f(coll[index], index)) {
+ result.push(coll[index]);
+ }
+ }
+ return result;
}
else {
var i = 0;
- return reduce(coll, function(result, x) {
- if(f(x, i++)) {
- return append(result, x);
+ return reduce(coll, function(result, input) {
+ if(f(input, i++)) {
+ return append(result, input);
}
return result;
}, empty(coll));
@@ -281,17 +299,6 @@ var transducers =
return filter(function(x) { return !f(x); }, coll);
}
- // function takeWhile(f, coll) {
- // if(coll) {
- // reduce(coll, function(result, x) {
- // if(x) {
- // return append(result, x);
- // }
- // return REDUCE_STOP;
- // }, empty(coll));
- // }
- // }
-
function keep(f, coll) {
return filter(function(x) { return x != null }, coll);
}
@@ -302,10 +309,10 @@ var transducers =
if(coll) {
return reduce(
coll,
- function(result, x) {
- if(x !== last) {
- last = x;
- return append(result, x);
+ function(result, input) {
+ if(input !== last) {
+ last = input;
+ return append(result, input);
}
return result;
},
@@ -314,33 +321,169 @@ var transducers =
}
return function(r) {
- return function(result, x) {
- if(x !== last) {
- last = x;
- r(result, x);
+ return function(result, input) {
+ if(input !== last) {
+ last = input;
+ r(result, input);
}
return result;
};
}
}
- function take(coll, n) {
- if(isNumber(n)) {
- var result = empty(coll);
- return iterate(coll, function(x, i) {
- if(i + 1 <= n) {
- result = append(result, x);
+ function takeWhile(f, coll) {
+ if(coll) {
+ if(isArray(coll)) {
+ var result = [];
+ var index = -1;
+ var len = coll.length;
+ while(++index < len) {
+ if(f(coll[index])) {
+ result.push(coll[index]);
+ }
+ else {
+ break;
+ }
+ }
+ return result;
+ }
+ else {
+ return reduce(coll, function(result, input) {
+ if(f(input)) {
+ return append(result, input);
+ }
+ return new Reduced(result);
+ }, empty(coll));
+ }
+ }
+
+ return function(r) {
+ return function(result, input) {
+ if(f(input)) {
+ return r(result, input);
+ }
+ return new Reduced(result);
+ };
+ }
+ }
+
+ function take(n, coll) {
+ if(coll) {
+ if(isArray(coll)) {
+ var result = [];
+ var index = -1;
+ var len = coll.length;
+ while(++index < n && index < len) {
+ result.push(coll[index]);
}
- else {
- return Iterated(result);
+ return result;
+ }
+ else {
+ var i = 0;
+ return reduce(coll, function(result, input) {
+ if(i++ < n) {
+ return append(result, input);
+ }
+ return new Reduced(result);
+ }, empty(coll));
+ }
+ }
+
+ return function(r) {
+ var i = 0;
+ return function(result, input) {
+ if(i++ < n) {
+ return r(result, input);
}
- });
+ return new Reduced(result);
+ };
}
- else {
- n = coll;
+ }
+
+ function drop(n, coll) {
+ if(coll) {
+ if(isArray(coll)) {
+ var result = [];
+ var index = n - 1;
+ var len = coll.length;
+ while(++index < len) {
+ result.push(coll[index]);
+ }
+ return result;
+ }
+ else {
+ var i = 0;
+ return reduce(coll, function(result, input) {
+ if((i++) + 1 > n) {
+ return append(result, input);
+ }
+ return result;
+ }, empty(coll));
+ }
+ }
+
+ return function(r) {
+ var i = 0;
+ return function(result, input) {
+ if((i++) + 1 > n) {
+ return r(result, input);
+ }
+ return result;
+ };
}
+ }
+ function dropWhile(f, coll) {
+ if(coll) {
+ if(isArray(coll)) {
+ var result = [];
+ var index = -1;
+ var len = coll.length;
+ var dropping = true;
+ while(++index < len) {
+ if(dropping) {
+ if(f(coll[index])) {
+ continue;
+ }
+ else {
+ dropping = false;
+ }
+ }
+ result.push(coll[index]);
+ }
+ return result;
+ }
+ else {
+ var dropping = true;
+ return reduce(coll, function(result, input, i) {
+ if(dropping) {
+ if(f(input)) {
+ return result;
+ }
+ else {
+ dropping = false;
+ }
+ }
+ return append(result, input);
+ }, empty(coll));
+ }
+ }
+
+ return function(r) {
+ var dropping = true;
+ return function(result, input, i) {
+ if(dropping) {
+ if(f(input)) {
+ return result;
+ }
+ else {
+ dropping = false;
+ }
+ }
+ return r(result, input);
+ };
+ }
}
// pure transducers (doesn't take collections)
@@ -357,10 +500,11 @@ var transducers =
module.exports = {
reduce: reduce,
- iterate: iterate,
+ Reduced: Reduced,
append: append,
empty: empty,
transduce: transduce,
+ sequence: sequence,
into: into,
compose: compose,
map: map,
@@ -369,7 +513,11 @@ var transducers =
cat: cat,
mapcat: mapcat,
keep: keep,
- dedupe: dedupe
+ dedupe: dedupe,
+ take: take,
+ takeWhile: takeWhile,
+ drop: drop,
+ dropWhile: dropWhile
};
| 229 | rebuild browser | 81 | .js | js | bsd-2-clause | jlongster/transducers.js |
10069336 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
</head>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= @current_env %></p>
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Fix URLs to replace http with https
<DFF> @@ -21,7 +21,7 @@
</div>
<div id="footer">
- <p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
+ <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
| 1 | Fix URLs to replace http with https | 1 | .erb | erb | mit | splitrb/split |
10069337 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
</head>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= @current_env %></p>
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Fix URLs to replace http with https
<DFF> @@ -21,7 +21,7 @@
</div>
<div id="footer">
- <p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
+ <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
| 1 | Fix URLs to replace http with https | 1 | .erb | erb | mit | splitrb/split |
10069338 | <NME> layout.erb
<BEF> <!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css">
<link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src='<%= url 'dashboard.js' %>'></script>
<script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script>
<script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script>
<title>Split</title>
</head>
<body>
<div class="header">
<h1>Split Dashboard</h1>
<p class="environment"><%= @current_env %></p>
</div>
<div id="main">
<%= yield %>
</div>
<div id="footer">
<p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
<MSG> Fix URLs to replace http with https
<DFF> @@ -21,7 +21,7 @@
</div>
<div id="footer">
- <p>Powered by <a href="http://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
+ <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p>
</div>
</body>
</html>
| 1 | Fix URLs to replace http with https | 1 | .erb | erb | mit | splitrb/split |
10069339 | <NME> transducers.js
<BEF>
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
iterator: symbolExists ? Symbol.iterator : '@@iterator'
};
function throwProtocolError(name, coll) {
throw new Error("don't know how to " + name + " collection: " +
coll);
}
function fulfillsProtocol(obj, name) {
if(name === 'iterator') {
// Accept ill-formed iterators that don't conform to the
// protocol by accepting just next()
return obj[protocols.iterator] || obj.next;
}
return obj[protocols[name]];
}
function getProtocolProperty(obj, name) {
return obj[protocols[name]];
}
function iterator(coll) {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
else if(isObject(coll)) {
return new ObjectIterator(coll);
}
}
function ArrayIterator(arr) {
this.arr = arr;
this.index = 0;
}
ArrayIterator.prototype.next = function() {
if(this.index < this.arr.length) {
return {
value: this.arr[this.index++],
done: false
};
}
return {
done: true
}
};
function ObjectIterator(obj) {
this.obj = obj;
this.keys = Object.keys(obj);
this.index = 0;
}
ObjectIterator.prototype.next = function() {
if(this.index < this.keys.length) {
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
}
function isNumber(x) {
return typeof x === 'number';
}
function Reduced(value) {
this['@@transducer/reduced'] = true;
this['@@transducer/value'] = value;
}
function isReduced(x) {
return (x instanceof Reduced) || (x && x['@@transducer/reduced']);
}
function deref(x) {
return x['@@transducer/value'];
}
/**
* This is for transforms that may call their nested transforms before
* Reduced-wrapping the result (e.g. "take"), to avoid nested Reduced.
*/
function ensureReduced(val) {
if(isReduced(val)) {
return val;
} else {
return new Reduced(val);
}
}
/**
* This is for tranforms that call their nested transforms when
* performing completion (like "partition"), to avoid signaling
* termination after already completing.
*/
function ensureUnreduced(v) {
if(isReduced(v)) {
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform['@@transducer/step'](result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform['@@transducer/result'](result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
result = xform['@@transducer/step'](result, val.value);
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
return xform['@@transducer/result'](result);
}
throwProtocolError('iterate', coll);
}
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
init = xform['@@transducer/init']();
}
return reduce(coll, xform, init);
}
function compose() {
var funcs = Array.prototype.slice.call(arguments);
return function(r) {
var value = r;
for(var i=funcs.length-1; i>=0; i--) {
value = funcs[i](value);
}
return value;
}
}
// transformations
function transformer(f) {
var t = {};
t['@@transducer/init'] = function() {
throw new Error('init value unavailable');
};
t['@@transducer/result'] = function(v) {
return v;
};
t['@@transducer/step'] = f;
return t;
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
else {
switch(count) {
case 1:
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
function arrayMap(arr, f, ctx) {
var index = -1;
var length = arr.length;
var result = Array(length);
f = bound(f, ctx, 2);
while (++index < length) {
result[index] = f(arr[index], index);
}
return result;
}
function arrayFilter(arr, f, ctx) {
var len = arr.length;
var result = [];
f = bound(f, ctx, 2);
for(var i=0; i<len; i++) {
if(f(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
}
function Map(f, xform) {
this.xform = xform;
this.f = f;
}
Map.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Map.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Map.prototype['@@transducer/step'] = function(res, input) {
return this.xform['@@transducer/step'](res, this.f(input));
};
function map(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(coll, f, ctx);
}
return seq(coll, map(f));
}
return function(xform) {
return new Map(f, xform);
}
}
function Filter(f, xform) {
this.xform = xform;
this.f = f;
}
Filter.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Filter.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Filter.prototype['@@transducer/step'] = function(res, input) {
if(this.f(input)) {
return this.xform['@@transducer/step'](res, input);
}
return res;
};
function filter(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayFilter(coll, f, ctx);
}
return seq(coll, filter(f));
}
return function(xform) {
return new Filter(f, xform);
};
}
function remove(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
return filter(coll, function(x) { return !f(x); });
}
function keep(coll) {
return filter(coll, function(x) { return x != null });
}
function Dedupe(xform) {
this.xform = xform;
this.last = undefined;
}
Dedupe.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Dedupe.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Dedupe.prototype['@@transducer/step'] = function(result, input) {
if(input !== this.last) {
this.last = input;
return this.xform['@@transducer/step'](result, input);
}
return result;
};
function dedupe(coll) {
if(coll) {
return seq(coll, dedupe());
}
return function(xform) {
return new Dedupe(xform);
}
}
function TakeWhile(f, xform) {
this.xform = xform;
this.f = f;
}
TakeWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.f(input)) {
return this.xform['@@transducer/step'](result, input);
}
return new Reduced(result);
};
function takeWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, takeWhile(f));
}
return function(xform) {
return new TakeWhile(f, xform);
}
}
function Take(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Take.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Take.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Take.prototype['@@transducer/step'] = function(result, input) {
if (this.i < this.n) {
result = this.xform['@@transducer/step'](result, input);
if(this.i + 1 >= this.n) {
// Finish reducing on the same step as the final value. TODO:
// double-check that this doesn't break any semantics
result = ensureReduced(result);
}
}
this.i++;
return result;
};
function take(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, take(n));
}
return function(xform) {
return new Take(n, xform);
}
}
function Drop(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Drop.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Drop.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Drop.prototype['@@transducer/step'] = function(result, input) {
if(this.i++ < this.n) {
return result;
}
return this.xform['@@transducer/step'](result, input);
};
function drop(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, drop(n));
}
return function(xform) {
return new Drop(n, xform);
}
}
function DropWhile(f, xform) {
this.xform = xform;
this.f = f;
this.dropping = true;
}
DropWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
DropWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
DropWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
}
else {
this.dropping = false;
}
}
return this.xform['@@transducer/step'](result, input);
};
function dropWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, dropWhile(f));
}
return function(xform) {
return new DropWhile(f, xform);
}
}
function Partition(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Partition.prototype['@@transducer/result'] = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));
}
return this.xform['@@transducer/result'](v);
};
Partition.prototype['@@transducer/step'] = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform['@@transducer/step'](result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
}
return function(xform) {
return new Partition(n, xform);
};
}
var NOTHING = {};
function PartitionBy(f, xform) {
// TODO: take an "opts" object that allows the user to specify
// equality
this.f = f;
this.xform = xform;
this.part = [];
this.last = NOTHING;
}
PartitionBy.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
PartitionBy.prototype['@@transducer/result'] = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l)));
}
return this.xform['@@transducer/result'](v);
};
PartitionBy.prototype['@@transducer/step'] = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform['@@transducer/step'](result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
return seq(coll, partitionBy(f));
}
return function(xform) {
return new PartitionBy(f, xform);
};
};
}
// pure transducers (cannot take collections)
function Cat(xform) {
}
Cat.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Cat.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Cat.prototype['@@transducer/step'] = function(result, input) {
var xform = this.xform;
var newxform = {};
newxform['@@transducer/init'] = function() {
return xform['@@transducer/init']();
};
newxform['@@transducer/result'] = function(v) {
return v;
};
newxform['@@transducer/step'] = function(result, input) {
var val = xform['@@transducer/step'](result, input);
return isReduced(val) ? deref(val) : val;
};
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
else {
var keys = Object.keys(x);
var len = keys.length;
for(var i=0; i<len; i++) {
obj[keys[i]] = x[keys[i]];
}
}
return obj;
}
var arrayReducer = {};
arrayReducer['@@transducer/init'] = function() {
return [];
};
arrayReducer['@@transducer/result'] = function(v) {
return v;
};
arrayReducer['@@transducer/step'] = push;
var objReducer = {};
objReducer['@@transducer/init'] = function() {
return {};
};
objReducer['@@transducer/result'] = function(v) {
return v;
};
objReducer['@@transducer/step'] = merge;
// building new collections
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(coll['@@transducer/step']) {
var init;
if(coll['@@transducer/init']) {
init = coll['@@transducer/init']();
}
else {
init = new coll.constructor();
}
return transduce(coll, xform, coll, init);
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(to['@@transducer/step']) {
return transduce(from,
xform,
to,
to);
}
throwProtocolError('into', to);
}
// laziness
var stepper = {};
stepper['@@transducer/result'] = function(v) {
return isReduced(v) ? deref(v) : v;
};
stepper['@@transducer/step'] = function(lt, x) {
lt.items.push(x);
return lt.rest;
};
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
Stepper.prototype['@@transducer/step'] = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform['@@transducer/result'](this);
break;
}
// step
this.xform['@@transducer/step'](lt, n.value);
}
}
function LazyTransformer(xform, coll) {
this.iter = iterator(coll);
this.items = [];
this.stepper = new Stepper(xform, iterator(coll));
}
LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
LazyTransformer.prototype.next = function() {
this['@@transducer/step']();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype['@@transducer/step'] = function() {
if(!this.items.length) {
this.stepper['@@transducer/step'](this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
Reduced: Reduced,
isReduced: isReduced,
iterator: iterator,
push: push,
merge: merge,
transduce: transduce,
seq: seq,
toArray: toArray,
toObj: toObj,
toIter: toIter,
into: into,
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
range: range,
protocols: protocols,
LazyTransformer: LazyTransformer
};
<MSG> Merge pull request #29 from ubolonton/more-transforms
add interpose, repeat, takeNth
<DFF> @@ -598,6 +598,125 @@ function partitionBy(coll, f, ctx) {
};
}
+function Interpose(sep, xform) {
+ this.sep = sep;
+ this.xform = xform;
+ this.started = false;
+}
+
+Interpose.prototype.init = function() {
+ return this.xform.init();
+};
+
+Interpose.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+Interpose.prototype.step = function(result, input) {
+ if (this.started) {
+ var withSep = this.xform.step(result, this.sep);
+ if (isReduced(withSep)) {
+ return withSep;
+ } else {
+ return this.xform.step(withSep, input);
+ }
+ } else {
+ this.started = true;
+ return this.xform.step(result, input);
+ }
+};
+
+/**
+ * Returns a new collection containing elements of the given
+ * collection, separated by the specified separator. Returns a
+ * transducer if a collection is not provided.
+ */
+function interpose(coll, separator) {
+ if (arguments.length === 1) {
+ separator = coll;
+ return function(xform) {
+ return new Interpose(separator, xform);
+ };
+ }
+ return seq(coll, interpose(separator));
+}
+
+function Repeat(n, xform) {
+ this.xform = xform;
+ this.n = n;
+}
+
+Repeat.prototype.init = function() {
+ return this.xform.init();
+};
+
+Repeat.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+Repeat.prototype.step = function(result, input) {
+ var n = this.n;
+ var r = result;
+ for (var i = 0; i < n; i++) {
+ r = this.xform.step(r, input);
+ if (isReduced(r)) {
+ break;
+ }
+ }
+ return r;
+};
+
+/**
+ * Returns a new collection containing elements of the given
+ * collection, each repeated n times. Returns a transducer if a
+ * collection is not provided.
+ */
+function repeat(coll, n) {
+ if (arguments.length === 1) {
+ n = coll;
+ return function(xform) {
+ return new Repeat(n, xform);
+ };
+ }
+ return seq(coll, repeat(n));
+}
+
+function TakeNth(n, xform) {
+ this.xform = xform;
+ this.n = n;
+ this.i = -1;
+}
+
+TakeNth.prototype.init = function() {
+ return this.xform.init();
+};
+
+TakeNth.prototype.result = function(v) {
+ return this.xform.result(v);
+};
+
+TakeNth.prototype.step = function(result, input) {
+ this.i += 1;
+ if (this.i % this.n === 0) {
+ return this.xform.step(result, input);
+ }
+ return result;
+};
+
+/**
+ * Returns a new collection of every nth element of the given
+ * collection. Returns a transducer if a collection is not provided.
+ */
+function takeNth(coll, nth) {
+ if (arguments.length === 1) {
+ nth = coll;
+ return function(xform) {
+ return new TakeNth(nth, xform);
+ };
+ }
+ return seq(coll, takeNth(nth));
+}
+
// pure transducers (cannot take collections)
function Cat(xform) {
@@ -833,10 +952,13 @@ module.exports = {
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
+ takeNth: takeNth,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
+ interpose: interpose,
+ repeat: repeat,
range: range,
protocols: protocols,
| 122 | Merge pull request #29 from ubolonton/more-transforms | 0 | .js | js | bsd-2-clause | jlongster/transducers.js |
10069340 | <NME> version.rb
<BEF> module Split
MAJOR = 0
MINOR = 4
TINY = 5
VERSION = [MAJOR, MINOR, TINY].join('.')
end
<MSG> Version 0.4.6
<DFF> @@ -1,6 +1,6 @@
module Split
MAJOR = 0
MINOR = 4
- TINY = 5
+ TINY = 6
VERSION = [MAJOR, MINOR, TINY].join('.')
end
| 1 | Version 0.4.6 | 1 | .rb | rb | mit | splitrb/split |
10069341 | <NME> version.rb
<BEF> module Split
MAJOR = 0
MINOR = 4
TINY = 5
VERSION = [MAJOR, MINOR, TINY].join('.')
end
<MSG> Version 0.4.6
<DFF> @@ -1,6 +1,6 @@
module Split
MAJOR = 0
MINOR = 4
- TINY = 5
+ TINY = 6
VERSION = [MAJOR, MINOR, TINY].join('.')
end
| 1 | Version 0.4.6 | 1 | .rb | rb | mit | splitrb/split |
10069342 | <NME> version.rb
<BEF> module Split
MAJOR = 0
MINOR = 4
TINY = 5
VERSION = [MAJOR, MINOR, TINY].join('.')
end
<MSG> Version 0.4.6
<DFF> @@ -1,6 +1,6 @@
module Split
MAJOR = 0
MINOR = 4
- TINY = 5
+ TINY = 6
VERSION = [MAJOR, MINOR, TINY].join('.')
end
| 1 | Version 0.4.6 | 1 | .rb | rb | mit | splitrb/split |
10069343 | <NME> version.rb
<BEF> module Split
VERSION = "0.2.4"
end
VERSION = "4.0.1"
end
<MSG> Version 0.3.0
<DFF> @@ -1,3 +1,3 @@
module Split
- VERSION = "0.2.4"
+ VERSION = "0.3.0"
end
| 1 | Version 0.3.0 | 1 | .rb | rb | mit | splitrb/split |
10069344 | <NME> version.rb
<BEF> module Split
VERSION = "0.2.4"
end
VERSION = "4.0.1"
end
<MSG> Version 0.3.0
<DFF> @@ -1,3 +1,3 @@
module Split
- VERSION = "0.2.4"
+ VERSION = "0.3.0"
end
| 1 | Version 0.3.0 | 1 | .rb | rb | mit | splitrb/split |
10069345 | <NME> version.rb
<BEF> module Split
VERSION = "0.2.4"
end
VERSION = "4.0.1"
end
<MSG> Version 0.3.0
<DFF> @@ -1,3 +1,3 @@
module Split
- VERSION = "0.2.4"
+ VERSION = "0.3.0"
end
| 1 | Version 0.3.0 | 1 | .rb | rb | mit | splitrb/split |
10069346 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
:my_experiment => {
:alternatives => [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment"}
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: ""}
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Merge pull request #680 from splitrb/enable-rubocop-ci
Enable rubocop on Github Actions
<DFF> @@ -203,10 +203,10 @@ describe Split::Dashboard do
end
describe "initialize experiment" do
- before do
+ before do
Split.configuration.experiments = {
- :my_experiment => {
- :alternatives => [ "control", "alternative" ],
+ my_experiment: {
+ alternatives: [ "control", "alternative" ],
}
}
end
@@ -214,14 +214,14 @@ describe Split::Dashboard do
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
- post "/initialize_experiment", { experiment: "my_experiment"}
+ post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
- post "/initialize_experiment", { experiment: ""}
+ post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
| 5 | Merge pull request #680 from splitrb/enable-rubocop-ci | 5 | .rb | rb | mit | splitrb/split |
10069347 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
:my_experiment => {
:alternatives => [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment"}
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: ""}
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Merge pull request #680 from splitrb/enable-rubocop-ci
Enable rubocop on Github Actions
<DFF> @@ -203,10 +203,10 @@ describe Split::Dashboard do
end
describe "initialize experiment" do
- before do
+ before do
Split.configuration.experiments = {
- :my_experiment => {
- :alternatives => [ "control", "alternative" ],
+ my_experiment: {
+ alternatives: [ "control", "alternative" ],
}
}
end
@@ -214,14 +214,14 @@ describe Split::Dashboard do
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
- post "/initialize_experiment", { experiment: "my_experiment"}
+ post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
- post "/initialize_experiment", { experiment: ""}
+ post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
| 5 | Merge pull request #680 from splitrb/enable-rubocop-ci | 5 | .rb | rb | mit | splitrb/split |
10069348 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
:my_experiment => {
:alternatives => [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment"}
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: ""}
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Merge pull request #680 from splitrb/enable-rubocop-ci
Enable rubocop on Github Actions
<DFF> @@ -203,10 +203,10 @@ describe Split::Dashboard do
end
describe "initialize experiment" do
- before do
+ before do
Split.configuration.experiments = {
- :my_experiment => {
- :alternatives => [ "control", "alternative" ],
+ my_experiment: {
+ alternatives: [ "control", "alternative" ],
}
}
end
@@ -214,14 +214,14 @@ describe Split::Dashboard do
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
- post "/initialize_experiment", { experiment: "my_experiment"}
+ post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
- post "/initialize_experiment", { experiment: ""}
+ post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
| 5 | Merge pull request #680 from splitrb/enable-rubocop-ci | 5 | .rb | rb | mit | splitrb/split |
10069349 | <NME> version.rb
<BEF> module Split
VERSION = "0.3.1"
end
VERSION = "4.0.1"
end
<MSG> Version 0.3.2
<DFF> @@ -1,3 +1,3 @@
module Split
- VERSION = "0.3.1"
+ VERSION = "0.3.2"
end
| 1 | Version 0.3.2 | 1 | .rb | rb | mit | splitrb/split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.