Using rails presenters - memoizable getting deprecated in 3.1 - use ||= instead?

ぃ、小莉子 提交于 2019-12-04 22:56:58


Issue: To avoid creating multiple objects or multiple queries when possible.

I am using Presenters with rails as a Best Practice.

I am following advice that says that it would be good to use "extend ActiveSupport.Memoizable" (and then memoize :method(s) to use them) over setting up items with @the_record = record ||= @record style because of a couple of issues - false or nil not getting stored so the query gets called again and also that memoizable uses the cache better (i.e. uses it!).

However I see that memoizable is getting deprecated in rails 3.1 Notes i github under carrierwave and with statement: "DEPRECATION WARNING: ActiveSupport::Memoizable is deprecated and will be removed in future releases,simply use Ruby memoization pattern instead. (called from extend at /Users/kain/.rvm/gems/ruby-1.9.3-preview1/bundler/gems/carrierwave-c4459179b0f8/lib/carrierwave/mount.rb:284".

Maybe it's been resolved though? Anyone know?

Any suggestions about the best practice to use going forward? Use the ||= syntax? What about the above issues?


The ||= method is great for things that return values that evaluate as true, but it doesn't work very well for things that don't. memoize does work around this by trapping these conditions and returning accordingly. You might take an approach like this if you want to accommodate nil:

def some_method
  return @some_method if (instance_variable_defined?(:"@some_method"))

  @some_method = begin

This just checks if the variable is defined, not if it is set, which is an important distinction in your case.

I'm not sure why you think it's being deprecated [Note from Michael, it's deprecated in 3.2, see note below]. The documentation indicates it's still current in 3.1. Sometimes implementations are marked as "deprecated" when they're being moved from one module to another, but the facility remains available.