3

I have a mixin that can show up in several different areas of our codebase. In a couple of cases there is, or was, an edge case where the module's use of instance variables conflicted with instance variables used by the classes.

Prepending variable names @__like_this was one solution, but the other we came up with was more sophisticated, having this general structure, in which the accessor methods are closures:

module HiddenValue
  def initialize
    hidden_value = nil
    define_singleton_method :value, ->() { hidden_value }
    define_singleton_method :value=, ->(v) { hidden_value = v }
    super
  end
end

class RealClass
  include HiddenValue
  # [...]
end

foo = RealClass.new
foo.value = 123
foo.value # => 123

Is this bad style? It means that all methods wanting direct access to the variable must be defined dynamically inside initialize, and that could get ugly. Is there a cleaner way? Or is this the closest we'll get to a module-level "lexical"-ish scoped instance variable?

4

0 に答える 0