Skip to content

Commit ea59fb5

Browse files
authored
Optimize API Hash objects (#528)
* Normalize API structure with a template API_SCAFFOLD is the base hash with each key pointing to a `nil` value. When merged with the API generated via calling `#hash_for_api`, the values of the base API will get updated. Therefore, the first two keys of the final api hash from calling `#to_api` will always be "name" and "path". The url fields ("http_url", "api_url", and collections' "entries_url") are injected towards the end so that they are always the last keys of the api hash. * Don't allocate new Hash objects for every merge
1 parent f0cf011 commit ea59fb5

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

lib/jekyll-admin/apiable.rb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ module JekyllAdmin
55
# additional, API-specific functionality without duplicating logic
66
module APIable
77
CONTENT_FIELDS = %w(next previous content excerpt).freeze
8+
API_SCAFFOLD = %w(name path).map { |i| [i, nil] }.to_h.freeze
89

910
# Returns a hash suitable for use as an API response.
1011
#
@@ -20,15 +21,15 @@ module APIable
2021
# include_content - if true, includes the content in the respond, false by default
2122
# to support mapping on indexes where we only want metadata
2223
#
23-
#
2424
# Returns a hash (which can then be to_json'd)
25+
#
26+
# rubocop:disable Metrics/AbcSize
2527
def to_api(include_content: false)
26-
output = hash_for_api
27-
output = output.merge(url_fields)
28+
output = API_SCAFFOLD.merge hash_for_api
2829

2930
# Include content, if requested, otherwise remove it
3031
if include_content
31-
output = output.merge(content_fields)
32+
output.merge!(content_fields)
3233
else
3334
CONTENT_FIELDS.each { |field| output.delete(field) }
3435
end
@@ -41,6 +42,8 @@ def to_api(include_content: false)
4142
# array with each rendered document, which we don't want.
4243
if is_a?(Jekyll::Collection)
4344
output.delete("docs")
45+
output["name"] = label
46+
output["path"] = relative_directory
4447
output["entries_url"] = entries_url
4548
end
4649

@@ -51,8 +54,10 @@ def to_api(include_content: false)
5154

5255
output["from_theme"] = from_theme_gem? if is_a?(Jekyll::StaticFile)
5356

57+
output.merge!(url_fields)
5458
output
5559
end
60+
# rubocop:enable Metrics/AbcSize
5661

5762
private
5863

0 commit comments

Comments
 (0)