mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
String/Lambda support for conditional attributes/associations
This commit is contained in:
@@ -239,27 +239,55 @@ module ActiveModel
|
||||
end
|
||||
end
|
||||
|
||||
# rubocop:disable Metrics/AbcSize
|
||||
def test_conditional_associations
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
belongs_to :if_assoc_included, if: :true
|
||||
belongs_to :if_assoc_excluded, if: :false
|
||||
belongs_to :unless_assoc_included, unless: :false
|
||||
belongs_to :unless_assoc_excluded, unless: :true
|
||||
model = ::Model.new(true: true, false: false)
|
||||
|
||||
def true
|
||||
true
|
||||
scenarios = [
|
||||
{ options: { if: :true }, included: true },
|
||||
{ options: { if: :false }, included: false },
|
||||
{ options: { unless: :false }, included: true },
|
||||
{ options: { unless: :true }, included: false },
|
||||
{ options: { if: 'object.true' }, included: true },
|
||||
{ options: { if: 'object.false' }, included: false },
|
||||
{ options: { unless: 'object.false' }, included: true },
|
||||
{ options: { unless: 'object.true' }, included: false },
|
||||
{ options: { if: -> { object.true } }, included: true },
|
||||
{ options: { if: -> { object.false } }, included: false },
|
||||
{ options: { unless: -> { object.false } }, included: true },
|
||||
{ options: { unless: -> { object.true } }, included: false },
|
||||
{ options: { if: -> (s) { s.object.true } }, included: true },
|
||||
{ options: { if: -> (s) { s.object.false } }, included: false },
|
||||
{ options: { unless: -> (s) { s.object.false } }, included: true },
|
||||
{ options: { unless: -> (s) { s.object.true } }, included: false }
|
||||
]
|
||||
|
||||
scenarios.each do |s|
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
belongs_to :association, s[:options]
|
||||
|
||||
def true
|
||||
true
|
||||
end
|
||||
|
||||
def false
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
def false
|
||||
false
|
||||
hash = serializable(model, serializer: serializer).serializable_hash
|
||||
assert_equal(s[:included], hash.key?(:association), "Error with #{s[:options]}")
|
||||
end
|
||||
end
|
||||
|
||||
def test_illegal_conditional_associations
|
||||
exception = assert_raises(TypeError) do
|
||||
Class.new(ActiveModel::Serializer) do
|
||||
belongs_to :x, if: nil
|
||||
end
|
||||
end
|
||||
|
||||
model = ::Model.new
|
||||
hash = serializable(model, serializer: serializer).serializable_hash
|
||||
expected = { if_assoc_included: nil, unless_assoc_included: nil }
|
||||
|
||||
assert_equal(expected, hash)
|
||||
assert_match(/:if should be a Symbol, String or Proc/, exception.message)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user