本文介绍了如何提升attr_accessor中的红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个(类)方法 attr_accessor_with_client_reset ,它做同样的事情为 attr_accessor中,但每一个作家它另外执行

I want to implement a (class) method attr_accessor_with_client_reset, which does the same thing as attr_accessor, but on every writer it additionally executes

@client = nil

因此​​,例如,

So, for example,

attr_accessor_with_client_reset :foo

应该产生相同的结果。

should produce the same result as

attr_reader :foo

def foo=(value)
  @foo = value
  @client = nil
end

我如何做到这一点?

How do I achieve this?

推荐答案

Sergio的解决方案是好的,但不必要的复杂性:没有必要重复 attr_reader 的行为,可以直接委托给它。而且也没有必要让所有这双模块包括钩两轮牛车。另外, attr_accessor中需要多个名字,所以 attr_accessor_with_client_reset 也应该这样。

Sergio's solution is good, but needlessly complex: there's no need to duplicate the behavior of attr_reader, you can just delegate to it. And there's no need for all this double module include hook hackery. Plus, attr_accessor takes multiple names, so attr_accessor_with_client_reset should, too.

module AttrAccessorWithClientReset
  def attr_accessor_with_client_reset(*names)
    attr_reader *names

    names.each do |name|
      define_method :"#{name}=" do |v|
        instance_variable_set(:"@#{name}", v)
        @client = nil
      end
    end
  end
end

class Foo
  extend AttrAccessorWithClientReset

  attr_reader :client
  def initialize
    @foo = 0
    @client = 'client'
  end

  attr_accessor_with_client_reset :foo
end

f = Foo.new
f.foo    # => 0
f.client # => "client"
f.foo = 1
f.foo    # => 1
f.client # => nil

这篇关于如何提升attr_accessor中的红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:50