Skip to content
This repository was archived by the owner on Oct 19, 2018. It is now read-only.

Commit c2efee0

Browse files
committed
Cache calculated params
1 parent 91e0a5f commit c2efee0

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

lib/react/component/props_wrapper.rb

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,17 @@ def self.define_param(name, param_type)
2727
end
2828
else
2929
define_method("#{name}") do
30-
if param_type.respond_to? :_react_param_conversion
31-
param_type._react_param_conversion props[name]
32-
elsif param_type.is_a?(Array) &&
33-
param_type[0].respond_to?(:_react_param_conversion)
34-
props[name].collect do |param|
35-
param_type[0]._react_param_conversion param
30+
fetch_from_cache(name) do
31+
if param_type.respond_to? :_react_param_conversion
32+
param_type._react_param_conversion props[name]
33+
elsif param_type.is_a?(Array) &&
34+
param_type[0].respond_to?(:_react_param_conversion)
35+
props[name].collect do |param|
36+
param_type[0]._react_param_conversion param
37+
end
38+
else
39+
props[name]
3640
end
37-
else
38-
props[name]
3941
end
4042
end
4143
end
@@ -51,6 +53,18 @@ def [](prop)
5153

5254
private
5355

56+
def fetch_from_cache(name)
57+
last, value = cache[name]
58+
return value if last.equal?(props[name])
59+
yield.tap do |value|
60+
cache[name] = [props[name], value]
61+
end
62+
end
63+
64+
def cache
65+
@cache ||= Hash.new { |h, k| h[k] = [] }
66+
end
67+
5468
def props
5569
component.props
5670
end

spec/react/param_declaration_spec.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,6 @@ def render
169169

170170
describe "converts params only once" do
171171
it "not on every access" do
172-
pending 'Fix after merging'
173172
stub_const "BazWoggle", Class.new
174173
BazWoggle.class_eval do
175174
def initialize(kind)
@@ -187,7 +186,6 @@ def render
187186
"#{params.foo.kind}"
188187
end
189188
end
190-
expect(Foo).to render
191189
expect(React.render_to_static_markup(React.create_element(Foo, foo: {bazwoggle: 1}))).to eq('<span>2</span>')
192190
end
193191

0 commit comments

Comments
 (0)