Skip to content

Instantly share code, notes, and snippets.

@donpadre
Forked from esmevane/jekyll-json.rb
Created February 23, 2017 07:53
Show Gist options
  • Save donpadre/fa14b013274b1b24d3e999b3713dd402 to your computer and use it in GitHub Desktop.
Save donpadre/fa14b013274b1b24d3e999b3713dd402 to your computer and use it in GitHub Desktop.
[ Jekyll / Ruby / Json ]: Generate json out of Jekyll posts
require 'json'
module Jekyll
module JsonContent
class Index < Jekyll::Page
attr_reader :page
def initialize site, base, dir, page
@site = site
@base = base
@dir = dir
@name = page.name
@page = page
self.process @name
self.read_yaml File.join(base, '_layouts'), 'api.json'
end
def permalink
page.url.sub(/html$/, 'json')
end
def output
{ title: page.data.fetch('title'), posts: post_list }.to_json
end
def post_list
site.posts.map { |post| Blurb.new(post).output }
end
end
class Page < Jekyll::Page
attr_reader :post
def initialize site, base, dir, post
@site = site
@base = base
@dir = dir
@name = post.name
@post = post
self.process @name
self.read_yaml File.join(base, '_layouts'), 'api.json'
end
def permalink
"#{post.id}.json"
end
def output
Hash.new.tap do |hash|
hash[:post] = { title: post.title, content: post.content }
hash[:next] = next_output if !post.next.nil?
hash[:previous] = prev_output if !post.previous.nil?
hash[:related_posts] = RelatedPosts.new(post, site).output
end.to_json
end
def prev_output
Blurb.new(post.previous).output
end
def next_output
Blurb.new(post.next).output
end
end
class Blurb
attr_reader :post
def initialize post
@post = post
end
def output
{ title: post.title, excerpt: post.excerpt, url: "#{post.id}.json" }
end
end
class RelatedPosts
attr_reader :post, :site
def initialize post, site
@post = post
@site = site
end
def output
return [] unless post.instance_of? Post
post.related_posts(site.posts).map { |post| Blurb.new(post).output }
end
end
end
class JsonPageGenerator < Generator
safe true
def generate(site)
dir = site.config.fetch('destination')
site.posts.each do |post|
site.pages << JsonContent::Page.new(site, site.source, dir, post)
end
index = site.pages.find { |page| page.name == 'index.html' }
site.pages << JsonContent::Index.new(site, site.source, dir, index)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment