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

1

6

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?

enter image description here

Roundhouse answered 28/10, 2011 at 13:31 Comment(0)
R
7

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
    ...
  end
end

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.

Rosierosily answered 28/10, 2011 at 15:34 Comment(3)
Well I looked around and maybe an older implementation was deprecated. Anyway I will go with Memoizable now I know I can rely on it on 3.1 Thx tadman!Roundhouse
Wait I found the warning, it's on the excellent railsbest course about presenters and memoization. They're well-known as the 'Rails for Zombies' course. Anyway they gave the info on memoization, said how ActiveSupport options was best and yet their actual code challenge say "ActiveSupport::Memoizable (note: ActiveSupport::Memoizable is deprecated in Rails 3.1)" ! so still not sure about that and if it gets deprecated is that because the above issues would be resolved, etc..Roundhouse
Deprecated as of 3.2: guides.rubyonrails.org/…Final

© 2022 - 2024 — McMap. All rights reserved.