Skip to content

Commit ce0fdec

Browse files
committed
Add lazy evaluation for data via read_value
1 parent 0366849 commit ce0fdec

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

lib/administrate/field/base.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,18 +65,22 @@ def self.local_partial_prefixes(look: :default)
6565
end
6666
end
6767

68-
def initialize(attribute, data, page, options = {})
68+
def initialize(attribute, raw_data, page, options = {})
6969
@attribute = attribute
7070
@page = page
7171
@resource = options.delete(:resource)
7272
@options = options
73-
@data = read_value(data)
73+
@raw_data = raw_data
7474
end
7575

7676
def html_class
7777
self.class.html_class
7878
end
7979

80+
def data
81+
read_value(@raw_data)
82+
end
83+
8084
def html_controller
8185
nil
8286
end
@@ -133,7 +137,7 @@ def required?
133137
end
134138
end
135139

136-
attr_reader :attribute, :data, :options, :page, :resource
140+
attr_reader :attribute, :options, :page, :resource
137141
attr_accessor :context
138142
end
139143
end

lib/administrate/field/has_many.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def more_than_limit?
7878
end
7979

8080
def data
81-
@data ||= associated_class.none
81+
super || associated_class.none
8282
end
8383

8484
def order_from_params(params)

spec/lib/fields/base_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,5 +300,15 @@
300300
expect(field.data).to eq(nil)
301301
end
302302
end
303+
304+
context "when context is set and a getter block is provided" do
305+
it "lazily reads the value from the context" do
306+
resource = double("Model")
307+
field = field_class.new(:attribute, :date, :page, resource: resource, getter: ->(f) { f.context.custom_value + " from block" })
308+
field.context = double("Context", custom_value: "custom value")
309+
310+
expect(field.data).to eq("custom value from block")
311+
end
312+
end
303313
end
304314
end

0 commit comments

Comments
 (0)