caiandhiscat
caiandhiscat

Reputation: 11

How to avoid repetitive function call to Ruby hash value?

pkg.A is called everywhere. I wonder how I can avoid this?
Also, how to simplify the repetitive condition like pkg.A.B.nil? and pkg.A.C.nil? ?
Thanks!

packages = result.packages.collect do |pkg|

{
        :origin => pkg.A.nil? ? nil : {
          :version => ("#{pkg.name}.#{pkg.A.B.version}.#{pkg.A.B.desc}" unless pkg.A.B.nil?),
          :branch => (pkg.A.B.branch unless pkg.A.B.nil?),
          :id => (pkg.A.B.id unless pkg.A.B.nil?),
          :set => (pkg.A.C.set unless pkg.A.C.nil?),
          :event => (pkg.A.C.event unless pkg.A.C.nil?)
        }.compact
}

Upvotes: 1

Views: 57

Answers (1)

spickermann
spickermann

Reputation: 106872

You could use the safe navigation operator that returns nil when called on nil.

And for the version identifier I would add a method to pkg.A.B.

packages = result.packages.collect do |pkg| 
  next unless pkg.A

  { 
    origin: {
      version: pkg.A.B&.version_identifier,
      branch:  pkg.A.B&.branch,
      id:      pkg.A.B&.id,
      set:     pkg.A.C&.set,
      event:   pkg.A.C&.event
    }.compact
  }
 end

# new method on `pkg.A.B`
def version_identifier
  [name, version, desc].join('.') # assuming `name` is available though inheritence or delegation.
end

You might also want to consider having a origin_hash method on pkg.A. Then the whole method could be simplified to:

packages = result.packages.collect { |pkg| pkg.A&.origin_hash }

Upvotes: 2

Related Questions