Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/static_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ def record(settings, &block)
index[id] = record
end

def attr_evaluated(*names)
attr_writer(*names)

names.each do |name|
define_method(name) do
attr_value = instance_variable_get("@#{name}")

if attr_value.respond_to?(:call)
instance_exec(&attr_value)
else
attr_value
end
end
end
end

private

def matches_attributes?(record:, attributes:)
Expand Down
46 changes: 46 additions & 0 deletions spec/static_association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@

class DummyClass
include StaticAssociation

attr_accessor :name
attr_evaluated :gender
end

class AssociationClass
attr_accessor :dummy_class_id
attr_accessor :dodo_class_id

extend StaticAssociation::AssociationHelpers

belongs_to_static :dummy_class
belongs_to_static :dodo_class, class_name: "DummyClass"
end
Expand Down Expand Up @@ -75,6 +78,49 @@ class AssociationClass
expect { DummyClass.record(id: 1) }.to change(DummyClass, :count).by(1)
end
end

context "when attr_evaluated defined attribute is assigned a lambda" do
it "evaluates the lambda when the attribute is read" do
record = DummyClass.record(id: 1) do
self.gender = -> do
if name == "Jane"
:female
else
:male
end
end
end

expect(record.gender).to eq(:male)
end
end

context "when attr_evaluated defined attribute is assigned a proc" do
it "evaluates the proc when the attribute is read" do
record = DummyClass.record(id: 1) do
self.name = "Jane"
self.gender = proc do
if @name == "Jane"
:female
else
:male
end
end
end

expect(record.gender).to eq(:female)
end
end

context "when attr_evaluated defined attribute is assigned a static value" do
it "returns the assigned value when the attribute is read" do
record = DummyClass.record(id: 1) do
self.gender = "Not disclosed"
end

expect(record.gender).to eq("Not disclosed")
end
end
end

describe ".all" do
Expand Down