Skip to content

Top level arrays and fragment caching #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,18 @@ end
json.partial! "api/comments/comments", comments: @message.comments
```

Jbuilder supports fragment caching similar to the `cache` helper in `ActionView`:

``` ruby
json.cache! ['v1', @person], :expires_in => 10.minutes do |json|
json.extract! @person, :name, :age

json.friends(@person.friends) do |json, friend|
json.extract! friend, :name, :age
end
end
```

Libraries similar to this in some form or another include:

* RABL: https://github.com/nesquena/rabl
Expand Down
47 changes: 42 additions & 5 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,23 @@ def child!
# end
#
# { "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
#
# If you omit the block then you can set the top level array directly:
#
# json.array! [1, 2, 3]
#
# [1,2,3]
def array!(collection)
@attributes = [] and return if collection.empty?

collection.each do |element|
child! do |child|
yield child, element
if block_given?
@attributes = [] and return if collection.empty?

collection.each do |element|
child! do |child|
yield child, element
end
end
else
@attributes = collection || []
end
end

Expand Down Expand Up @@ -134,6 +144,33 @@ def target!
ActiveSupport::JSON.encode @attributes
end

# Caches the json constructed within the block passed. Has the same signature as the `cache` helper
# method in `ActionView::Helpers::CacheHelper` and so can be used in the same way.
#
# Example:
#
# json.cache! ['v1', @person], :expires_in => 10.minutes do |json|
# json.extract! @person, :name, :age
# end
def cache!(key = nil, options = {}, &block)
cache_key = ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :jbuilder)
value = Rails.cache.read(cache_key, options)

if ! value
attributes = self.attributes!.clone
yield self
new_value = self.attributes!.is_a?(Hash) ? self.attributes!.diff(attributes) : self.attributes!
Rails.cache.write(cache_key, new_value, options)
else
if value.is_a?(Array)
self.array! value
else
value.each do |k, v|
self.set! k, v
end
end
end
end

private
def method_missing(method, *args)
Expand Down