Writing dynamic exposures by overriding initialize

Open
#257 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
35/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
ruby
Domain
api

Research direction

Start in entity.rb at line 175 and inspect how exposures are appended to root_exposures. Reproduce the duplicate-exposure behavior described in the issue and review the reported test coverage. Done means repeated dynamic exposure initialization no longer degrades performance and regression coverage passes.

Written by the indexing model from the issue text.

Description

I've got a project that was still running 0.4.8 where, for example, we have Arrival and Departure types of Flight records, and the consumer wanted fields labelled as such. Rather than writing a bunch of boilerplate like:

expose :blah, as: :departure_blah, if: if: lambda {|o,_p| o.type == "Departure" }

I overrode the entity child class's initialize method:

  def initialize(object, options = {})
    if object
      self.class.expose :blah, as: "#{type}_blah"
    end
    super(object, options)
  end

This worked fine but after (finally) upgrading to 0.6.0 this started causing duplicate exposures to be added the root_exposures class variable, steadily degrading performance over time. Changing line 175 of entity.rb to root_exposures << exposure unless root_exposures.include?(exposure) fixes the issue, I've got test coverage written for that but following along the instructions for contributing I just get permission denied errors when attempting to push my branch.

Looking at that old code I realize that was an awful kludgey way of going about it.

Dominant language
Ruby
Stars
729
Forks
154
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ruby-grape/grape-entity

All issues in ruby-grape/grape-entity

Similar issues

More Ruby issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.