From 96bc62c666b598c3dc7df7e2ec8a9b22625ed0af Mon Sep 17 00:00:00 2001
From: Parker Moore
Date: Fri, 4 Dec 2015 09:33:33 -0800
Subject: [PATCH] Add 'sample' Liquid filter
Equivalent to Array#sample functionality
---
lib/jekyll/filters.rb | 5 +++++
site/_docs/templates.md | 11 +++++++++++
test/test_filters.rb | 7 +++++++
3 files changed, 23 insertions(+)
diff --git a/lib/jekyll/filters.rb b/lib/jekyll/filters.rb
index 7e2d30f3..f3193f21 100644
--- a/lib/jekyll/filters.rb
+++ b/lib/jekyll/filters.rb
@@ -281,6 +281,11 @@ module Jekyll
new_ary
end
+ def sample(input)
+ return input unless input.respond_to?(:sample)
+ input.sample(1)
+ end
+
# Convert an object into its String representation for debugging
#
# input - The Object to be converted
diff --git a/site/_docs/templates.md b/site/_docs/templates.md
index 58e06c94..20a3a3f2 100644
--- a/site/_docs/templates.md
+++ b/site/_docs/templates.md
@@ -246,6 +246,17 @@ common tasks easier.
+
+
+ Sample
+ Pick a random value from an array.
+ |
+
+
+ {% raw %}{{ site.pages | sample }}{% endraw %}
+
+ |
+
diff --git a/test/test_filters.rb b/test/test_filters.rb
index cf4db89b..59b882f1 100644
--- a/test/test_filters.rb
+++ b/test/test_filters.rb
@@ -388,5 +388,12 @@ class TestFilters < JekyllUnitTest
end
end
+ context "sample filter" do
+ should "return a random item from the array" do
+ input = %w(hey there bernie)
+ assert_includes input, @filter.sample(input)
+ end
+ end
+
end
end