1

if I want to memoize the result of a method in a module, is that considered bad practice?

imagine I have a rails helper:

module FooHelper
  def values_for_thingie
    if some_condition && that_other_condition
      { a: "foo", b: "bar" }
    else
      { a: "bar", b: "baz" }
    end
  end
end

Let's assume a rails view is going to call this helper method multiple times .. one to get the value for "a", and another to get the value of "b"... Let's also assume that some_condition is a method that does something super complicated so we don't want that to get called more than once...

This can be solved by doing:

module FooHelper
  def values_for_thingie
    @values_for_thingie ||= \
      if some_condition && that_other_condition
        { a: "foo", b: "bar" }
      else
        { a: "bar", b: "baz" }
      end
  end
end

However, I don't like how this feels because this instance variable has nothing to do with an instance of FooHelper.. It's not really under its control. And so for that reason, it seems like this is not a good solution.

4

2 回答 2

1

如果条件在实例之间是恒定的,它可能应该是一个类/模块方法。然后,用于记忆的实例变量将是该类/方法的实例变量。没有错。或者,您可以将其保留为实例方法并使用类变量进行记忆。

于 2012-12-13T19:51:40.647 回答
1

您的实例变量不在您的模块中,而是在包含该模块的类的实例中。

在您的示例@values_for_thingie中,是在 FooHelper 中定义的,但将存在于 ActionView 实例中。

因此,如果 values_for_thingie 的结果必须在请求之间发生变化,那么您做对了。

但是,您应该考虑只记住在您的情况下需要一些时间才能运行的方法some_condition

于 2012-12-13T22:25:07.063 回答