Skip to content

Instantly share code, notes, and snippets.

@coderguy
Last active December 17, 2015 17:19
Show Gist options
  • Save coderguy/5645522 to your computer and use it in GitHub Desktop.
Save coderguy/5645522 to your computer and use it in GitHub Desktop.
The API for locomotive only returns slugs for children content. I wanted to be able to use the API to create a JSON only version of the site. This code does two things: 1. Creates a hash that includes all nested content for a content entry. 2. Overrides the presenter's as_json to allow it to display through the current API. So you can go to an e…
require_dependency Locomotive::Engine.root.join('app', 'models', 'locomotive', 'content_entry').to_s
require_dependency Locomotive::Engine.root.join('app', 'presenters', 'locomotive', 'content_entry_presenter').to_s
Locomotive::ContentEntry.class_eval do
def recursive_hash(depth=0)
base = custom_fields_basic_attributes
base[:id] = _id
base[:slug] = _slug
# only check belongs_to on depth of 1
if(depth === 0)
self.belongs_to_custom_fields.each do |name, _|
target = send(name.to_sym)
base[name.to_s] = target.recursive_hash(depth + 1)
end
end
(self.has_many_custom_fields + self.many_to_many_custom_fields).each do | name, _ |
list = send(name.to_sym).ordered
base[name.to_s] = list.map do |entry|
entry.recursive_hash(depth + 1)
end
end
base
end
end
Locomotive::ContentEntryPresenter.class_eval do
def as_json
self.__source.recursive_hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment