Skip to content

Commit

Permalink
WIP: fix read_value method in Administrate::Field::Base
Browse files Browse the repository at this point in the history
  • Loading branch information
goosys committed Sep 25, 2024
1 parent f377679 commit a575bde
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 7 deletions.
11 changes: 6 additions & 5 deletions lib/administrate/field/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@ def self.permitted_attribute(attr, _options = nil)

def initialize(attribute, data, page, options = {})
@attribute = attribute
@data = data
@page = page
@resource = options.delete(:resource)
@options = options
@data = read_value if @data.nil?
@data = read_value(data)
end

def html_class
Expand All @@ -53,15 +52,17 @@ def name
attribute.to_s
end

def read_value
def read_value(data = nil)
if options.key?(:getter)
if options[:getter].respond_to?(:call)
options[:getter].call(self)
else
resource&.public_send(options[:getter])
resource.try(options[:getter])
end
elsif data.nil?
resource.try(attribute)
else
resource&.public_send(attribute)
data
end
end

Expand Down
4 changes: 2 additions & 2 deletions spec/lib/fields/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,11 @@
end

it "reads the value from the resource with a custom getter block" do
resource = double
resource = double("Model", custom_getter: "value")
field = field_class.new(:attribute, :date, :page, resource: resource, getter: ->(field) { field.resource.custom_getter })

expect(resource).to receive(:custom_getter)
field.read_value
expect(field.read_value).to eq("value")
end

it "returns nil if the resource is nil" do
Expand Down
37 changes: 37 additions & 0 deletions spec/lib/fields/virtual_field_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
require "rails_helper"
require "administrate/field/base"

module Administrate
module Field
class VirtualField < Field::Base
def self.searchable?
false
end

def read_value(data = nil)
resource.inspect
end

def foobar
"This is a Foobar: #{data}"
end
end
end
end

describe Administrate::Field::VirtualField do
describe "#foobar" do
it "displays the foobar" do
resource = double("Model", inspect: "Inspecting")

field = Administrate::Field::VirtualField.new(
:virtual_field,
nil,
:show,
resource: resource
)

expect(field.foobar).to eq("This is a Foobar: Inspecting")
end
end
end

0 comments on commit a575bde

Please sign in to comment.