Add 'sample' Liquid filter

Equivalent to Array#sample functionality
This commit is contained in:
Parker Moore 2015-12-04 09:33:33 -08:00
parent b78d5085f1
commit 96bc62c666
3 changed files with 23 additions and 0 deletions

View File

@ -281,6 +281,11 @@ module Jekyll
new_ary new_ary
end end
def sample(input)
return input unless input.respond_to?(:sample)
input.sample(1)
end
# Convert an object into its String representation for debugging # Convert an object into its String representation for debugging
# #
# input - The Object to be converted # input - The Object to be converted

View File

@ -246,6 +246,17 @@ common tasks easier.
</p> </p>
</td> </td>
</tr> </tr>
<tr>
<td>
<p class="name"><strong>Sample</strong></p>
<p>Pick a random value from an array.</p>
</td>
<td class="align-center">
<p>
<code class="filter">{% raw %}{{ site.pages | sample }}{% endraw %}</code>
</p>
</td>
</tr>
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@ -388,5 +388,12 @@ class TestFilters < JekyllUnitTest
end end
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
end end