grape-entity
grape-entity copied to clipboard
Be able to use `using`, `proc` and `format_with` together
I am reporting as an issue what I found https://github.com/ruby-grape/grape-entity/pull/225.
When calling format_with: with a block or using: option, the formatter is ignored:
# formatter `foo` defined in a helper
Grape::Entity.format_with :foo do |value|
binding.pry
end
# formatter `foo` is not called, totally ignored
expose :users, using: Entities::MyEntity, format_with: :foo do |instance, _opt|
instance.users
end
# formatter `foo` is not called, totally ignored
expose :users, using: Entities::MyEntity, format_with: :foo
# formatter `foo` is not called, totally ignored
with_options(format_with: :foo) do
expose :users, using: Entities::MyEntity
end
# only this works
expose :users, format_with: :foo
I can even call a non-existing formatter and any error is raised:
# formatter `bar` does not exist, again, totally ignored
expose :users, using: Entities::MyEntity, format_with: :bar do |instance, _opt|
instance.users
end
# formatter `bar` does not exist, again, totally ignored
expose :users, using: Entities:: MyEntity, format_with: :bar
# formatter `bar` does not exist, again, totally ignored
with_options(format_with: :bar) do
expose :users, using: Entities::MyEntity
end
# only this raises the error:
# NoMethodError: undefined method `bar' for #<Entities...
expose :users, format_with: :bar
The way I found to format in the cases above where the formatter is ignored is to mokey-patching Entity.
# Gemfile
gem "grape", "~> 0.16.2"
gem "grape-entity", "~> 0.5.1"
I found out we in fact cannot use both using, proc, format_with and nesting together as coded https://github.com/ruby-grape/grape-entity/blob/master/lib/grape_entity/exposure.rb#L17.
It would be a nice feature.
Labeled this as a feature.
I found a way to achieve this with:
Grape::Entity.format_with :foo do |value|
Entities::MyEntity.represent(value)
end
expose :users, format_with: :foo
:format_with isn't applying the specified formatter to anything in a block. So if you do something like:
expose :that, format_with: :foo do |object, _options|
object.decorate.that
end
It won't ever apply the formatter to the exposed value. IMO this is a bug (formatter silently fails to be applied to the exposed value) and not a feature.