Created
January 8, 2017 06:38
-
-
Save ichiban/a7334bea675be47f8e06b1dd74103448 to your computer and use it in GitHub Desktop.
An easy way to implement HAL+JSON in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/views/partials/_links.json.jbuilder | |
json._links do | |
if object.is_a?(ActiveRecord::Relation) | |
json.self do | |
json.href url_for(object.klass) | |
end | |
else | |
json.self do | |
json.href url_for(object) | |
end | |
end | |
keys = [] | |
keys << :elements if object.is_a?(Enumerable) | |
keys += object.class.reflections.keys.map(&:to_sym) if object.is_a?(ActiveRecord::Base) | |
keys.each do |k| | |
json.set! k do | |
associations = :elements == k ? object : object.send(k) | |
if associations.is_a?(Enumerable) | |
json.array! associations do |association| | |
json.href url_for(association) | |
end | |
else | |
json.href url_for(associations) | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/views/actors/show.json.jbuilder | |
json.(@actor, :name) | |
json.partial! 'partials/links', object: @actor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment