Skip to content

Commit c78fd36

Browse files
committed
Reuse methods when template cache disabled
1 parent e2520c1 commit c78fd36

2 files changed

Lines changed: 16 additions & 7 deletions

File tree

lib/simple_json/simple_json_renderer.rb

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,26 @@ def load_template_from_file(template_path)
4646
end
4747

4848
def define_template_method(template_path, file_path)
49-
@template_num ||= 0
50-
@template_num += 1
51-
method_name = :"template_#{@template_num}"
52-
render_methods[template_path] = method_name
53-
SimpleJsonTemplate.new(file_path).define_to_class(self, method_name)
49+
template = SimpleJsonTemplate.new(file_path)
50+
code_hash = template.code.hash
51+
52+
render_methods[template_path] = render_methods_cache.fetch(code_hash) do
53+
@template_num ||= 0
54+
@template_num += 1
55+
method_name = :"template_#{@template_num}"
56+
template.define_to_class(self, method_name)
57+
render_methods_cache[code_hash] = method_name
58+
end
5459
end
5560

5661
def render_methods
5762
@render_methods ||= {}
5863
end
5964

65+
def render_methods_cache
66+
@render_methods_cache ||= {}
67+
end
68+
6069
def clear_renderers
6170
@render_methods = {}
6271
@templates_loaded = false

lib/simple_json/simple_json_template.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ def define_to_class(klass, method_name)
1414
method_name
1515
end
1616

17-
private
18-
1917
def code
2018
@code ||= lambda_stringify(@source)
2119
end
2220

21+
private
22+
2323
def lambda_stringify(source)
2424
return source if source.match?(/^(?:\s*(?:#.*?)?\n)*\s*->/)
2525

0 commit comments

Comments
 (0)