Skip to content

Commit

Permalink
Add predicate methods for CurrentAttributes
Browse files Browse the repository at this point in the history
Add support for predicate with no arguments
  • Loading branch information
Bodacious committed Jan 7, 2022
1 parent ad60a8b commit dd818ba
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
6 changes: 6 additions & 0 deletions activesupport/lib/active_support/current_attributes.rb
Expand Up @@ -112,6 +112,12 @@ def attribute(*names)
"attributes[:#{name}] = value" <<
"end"
end
owner.define_cached_method("#{name}?", namespace: :current_attributes) do |batch|
batch <<
"def #{name}?(value = nil)" <<
"value ? attributes[:#{name}] == value : attributes[:#{name}].present?" <<
"end"
end
end
end

Expand Down
37 changes: 37 additions & 0 deletions activesupport/test/current_attributes_test.rb
Expand Up @@ -176,6 +176,43 @@ def after_teardown
assert_equal true, Current.respond_to?("respond_to_test")
end

test "+attribute+? returns true if value set and no argument given" do
person = Person.new(42, "David", "Central Time (US & Canada)")
Current.person = person
assert Current.person?
end

test "+attribute+? returns false if value nil and no argument given" do
Current.world = nil
refute Current.world?
end

test "+attribute+? returns false if value blank and no argument" do
Current.world = ""
refute Current.world?
end

test "+attribute+? returns true if value matches argument" do
person = Person.new(42, "David", "Central Time (US & Canada)")
Current.person = person
assert Current.person?(person)
end

test "+attribute+? returns false if value doesn't match argument" do
person_a = Person.new(42, "David", "Central Time (US & Canada)")
person_b = Person.new(43, "Other Person", "Central Time (US & Canada)")
Current.person = person_a
refute Current.person?(person_b)
end

test "+attribute+? returns true in block Current.set" do
person = Person.new(42, "David", "Central Time (US & Canada)")
Current.set(person: person) do
assert Current.person?(person)
end
refute Current.person?(person)
end

test "CurrentAttributes use fiber-local variables" do
previous_level = ActiveSupport::IsolatedExecutionState.isolation_level
ActiveSupport::IsolatedExecutionState.isolation_level = :fiber
Expand Down

0 comments on commit dd818ba

Please sign in to comment.