grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

Be able to use `using`, `proc` and `format_with` together

Open glaucocustodio opened this issue 9 years ago • 3 comments

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.

glaucocustodio avatar Jun 23 '16 14:06 glaucocustodio

Labeled this as a feature.

dblock avatar Jun 26 '16 07:06 dblock

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

zhukovpe avatar Jul 07 '17 10:07 zhukovpe

: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.

allisonphillips avatar May 26 '21 18:05 allisonphillips