Skip to content

Commit

Permalink
store class names instead of classes in acts_as_ registries
Browse files Browse the repository at this point in the history
Storing classes in development may lead to problems when reloading
classes, as new versions of the class will be appended to the list, but
`instance` method will still find the old versions of the classes.

I considered adding caching for production environment, but additional
code is not justified by 3 times faster execution.

```ruby
require "benchmark/ips"

h = {"Project" => Project}

Benchmark.ips do |x|
  x.report("constantize") { "Project".constantize }

  x.report("hash access") { h["Project"] }

  x.compare!
end
```

```
Warming up --------------------------------------
         constantize     1.163M i/100ms
         hash access     3.397M i/100ms
Calculating -------------------------------------
         constantize     11.842M (± 1.5%) i/s -     59.291M in
5.007752s
         hash access     34.379M (± 1.3%) i/s -    173.239M in
5.039989s

Comparison:
         hash access: 34378546.0 i/s
         constantize: 11842325.0 i/s - 2.90x  slower
```
  • Loading branch information
toy committed Jun 27, 2024
1 parent b1bccd5 commit da1b658
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib_static/open_project/acts/registry_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ module OpenProject
module Acts
module RegistryMethods
def instance(model_name)
models.detect { |cls| cls.name == model_name.singularize.camelize }
class_name = model_name.singularize.camelize

class_name.constantize if class_names.include?(class_name)
end

def add(*models)
Expand All @@ -42,14 +44,14 @@ def add(*models)
raise ArgumentError.new("Model #{model} does not include #{acts_as_method_name}")
end

self.models << model
class_names << model.name
end
end

private

def models
@models ||= Set.new
def class_names
@class_names ||= Set.new
end
end
end
Expand Down

0 comments on commit da1b658

Please sign in to comment.