Skip to content

Commit

Permalink
Favoring explicit class declaration
Browse files Browse the repository at this point in the history
In helping track down #17041 I was looking at our cache
busting logic.  We were looking up a constant via the `.const_get` call
from a string already defined inline.  This refactor short-circuits
naming a string, capitalizing it, then looking in the class's registered
constants.

There's also a subtle bug in the original; When `provider` equals
"another_cache", the `#capitalize` method would return
`"Another_cache"`, whereas `#classify` will return `"AnotherCache"`.

Below are some benchmarks for the change.

```ruby
require "benchmark"

module EdgeCache
  class Bust
    def by_class
      Fastly
    end

    def by_const_get
      self.class.const_get("fastly".classify)
    end
  end
end

Benchmark.bmbm do |x|
  x.report("by_class") do
    1000.times do
      EdgeCache::Bust.new.by_class
    end
  end
  x.report("by_const_get") do
    1000.times do
      EdgeCache::Bust.new.by_const_get
    end
  end
end
```

```shell
> bin/rails runner /Users/jfriesen/git/forem/bench.rb

Rehearsal ------------------------------------------------
by_class       0.001239   0.000186   0.001425 (  0.001342)
by_const_get   0.011398   0.000136   0.011534 (  0.011538)
--------------------------------------- total: 0.012959sec

                   user     system      total        real
by_class       0.000973   0.000030   0.001003 (  0.000969)
by_const_get   0.011102   0.000032   0.011134 (  0.011104)
```
  • Loading branch information
jeremyf committed Mar 29, 2022
1 parent 1473e58 commit d435687
Showing 1 changed file with 3 additions and 9 deletions.
12 changes: 3 additions & 9 deletions app/services/edge_cache/bust.rb
Expand Up @@ -26,16 +26,10 @@ def call(paths)
private

def determine_provider_class
provider =
if fastly_enabled?
"fastly"
elsif nginx_enabled_and_available?
"nginx"
end
return self.class::Fastly if fastly_enabled?
return self.class::Nginx if nginx_enabled_and_available?

return unless provider

self.class.const_get(provider.capitalize)
nil
end

def fastly_enabled?
Expand Down

0 comments on commit d435687

Please sign in to comment.