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