Skip to content

Instantly share code, notes, and snippets.

@plusjade
Last active December 23, 2015 08:09
Show Gist options
  • Save plusjade/6605317 to your computer and use it in GitHub Desktop.
Save plusjade/6605317 to your computer and use it in GitHub Desktop.
Ruhoh plugin to pragmatically get a list of n random pages from an arbitrary pages collection.
# ./my-blog/plugins/pages_random.rb
module PagesRandom
# Return n random page objects.
# Limit can be set in config.yml:
# pages:
# random_limit: 10
def random
limit = config['random_limit'].to_i
limit = limit > 0 ? limit : 5
all.sample(limit)
end
# Return n random page objects.
# Limit can be set dynamically by chaining the method call:
# {{# pages.random_with_limit.25 }}
# <li><a href="{{ url }}">{{ title }}</a></li>
# {{/ pages.random_with_limit.25 }}
def random_with_limit
@random_with_limit ||= RandomProxy.new(self)
end
# Allows arbitrary responses to methods that can be cast to Integers.
# ex: random_with_limit.5 where "5" can be cast to an Integer
class RandomProxy < SimpleDelegator
def method_missing(name, *args, &block)
__getobj__.all.sample(name.to_s.to_i)
end
def respond_to?(method)
(method.to_s.to_i > 0) ? true : super
end
end
end
Ruhoh::Resources::Pages::CollectionView.send(:include, PagesRandom)

Usage

In your View

<h5>Random with config limit</h5>
<ul>
{{# pages.random }}
  <li><a href="{{ url }}">{{ title }}</a></li>
{{/ pages.random }}
</ul>

<h5>Random with embedded limit</h5>
<ul>
{{# pages.random_with_limit.4 }}
  <li><a href="{{ url }}">{{ title }}</a></li>
{{/ pages.random_with_limit.4 }}
</ul>

*Note this works on any collection not just "pages".

pages.random

Limit can be set in configuration:

pages:
  random_limit: 3 # defaults to 5 in the above example plugin

pages.random_with_limit

Limit can be set dynamically by chaining the method call:

limit: 1
{{# pages.random_with_limit.1 }}
  <li><a href="{{ url }}">{{ title }}</a></li>
{{/ pages.random_with_limit.1 }}

limit: 25
{{# pages.random_with_limit.25 }}
  <li><a href="{{ url }}">{{ title }}</a></li>
{{/ pages.random_with_limit.25 }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment