diff --git a/.travis.yml b/.travis.yml index 6c86836f..bf5d2d4c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,6 +19,9 @@ env: matrix: - TEST_SUITE=test - TEST_SUITE=cucumber +branches: + only: + - master before_script: bundle update script: script/cibuild notifications: diff --git a/lib/jekyll/filters.rb b/lib/jekyll/filters.rb index 7e2d30f3..2b1bf1af 100644 --- a/lib/jekyll/filters.rb +++ b/lib/jekyll/filters.rb @@ -281,6 +281,16 @@ module Jekyll new_ary end + def sample(input, num = 1) + return input unless input.respond_to?(:sample) + n = num.to_i rescue 1 + if n == 1 + input.sample + else + input.sample(n) + end + 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..fd42b6b1 100644 --- a/site/_docs/templates.md +++ b/site/_docs/templates.md @@ -246,6 +246,20 @@ common tasks easier.

+ + +

Sample

+

Pick a random value from an array. Optional: pick multiple values.

+ + +

+ {% raw %}{{ site.pages | sample }}{% endraw %} +

+

+ {% raw %}{{ site.pages | sample:2 }}{% endraw %} +

+ + diff --git a/test/test_filters.rb b/test/test_filters.rb index cf4db89b..dc51252e 100644 --- a/test/test_filters.rb +++ b/test/test_filters.rb @@ -388,5 +388,19 @@ 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 + + should "allow sampling of multiple values (n > 1)" do + input = %w(hey there bernie) + @filter.sample(input, 2).each do |val| + assert_includes input, val + end + end + end + end end