grape-entity
grape-entity copied to clipboard
Separate condition evaluations for same attribute
Consider the following:
with_options if: { kind: :short } do
expose :name do |obj, opts|
"#{obj.first_name[0]}. #{obj.last_name}"
end
end
with_options if: { kind: :full } do
expose :name do |obj, opts|
"#{obj.first_name} #{obj.last_name}"
end
end
Based on the above, I would expect that if :kind
is :short
then the value of :name
will be the first initial and last name, and if :kind
is :full
then the value will be the first and last name.
However, since these two exposures use the same attribute name, it's not possible to evaluated them both. The :name
attribute only retains the conditional options that are defined last because they replace any previously defined options for the :name
key in the the exposures hash.
This means that (for the code above) if :kind
is :short
then the :name
attribute will not be exposed at all.
My first idea was to append some sort of unique identifier to each key in the exposures hash, but this produced a bunch of errors in the specs because they access the keys in the exposures hash directly to test values, and do not know beforehand what unique ID will be added.
Any thoughts?
I think your example above is something we should support. Start by writing a test that demonstrates the problem, lets fix it.
@wyattisimo Why don't you do it a little bit more verbose?
expose :short_name, as: :name if: { kind: :short }
expose :full_name, as: :name if: { kind: :full }
def short_name
"#{object.first_name[0]}. #{oject.last_name}"
end
def full_name
"#{object.first_name} #{object.last_name}"
end
I think this should work allready.
I tried to solve it differently in #151, please look at it.