gpt4 book ai didi

ruby - 有什么方法可以检测 Ruby 中的属性变化吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:46 24 4
gpt4 key购买 nike

我有这个代码:

class Test
attr_accessor :test_attr
def initialize
@test_attr = ""
end

def test_attr_changed
p 'test_attr is changed: ' + @test_attr
end
end

当我更改属性 :test_attr 时:

test = Test.new
test.test_attr = "New value"

我希望它触发 test_attr_changed 函数并输出:

test_attr is changed: New value

在 Ruby 中有没有像 QML onChanged 信号那样的方法?

最佳答案

这是一个相当简单的实现,说明如何模块化此功能

module Overlord
module ClassMethods
def attr_watcher(*attrs)
attrs.each do |attr|
define_method(attr) {instance_variable_get("@#{attr}")}
define_method("#{attr}=") do |val|
changes[attr] << {new: val, old: send(attr), when: Time.now}
instance_variable_set("@#{attr}",val)
end
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
def changes
@changes ||= Hash.new {|h,k| h[k] = []}
end
end

class Test
include Overlord
attr_watcher :name
end

然后就简单了

t = Test.new
t.changes
#=> {}
t.name = "Mnky"
t.changes
#=> => {:name=>[{:new=>"Mnky", :old=>nil, :when=>2017-08-24 11:17:27 -0400}]}
t.name = "Other"
t.changes[:name]
#=> [
{:new=>"Mnky", :old=>nil, :when=>2017-08-24 11:17:27 -0400},
{:new=>"Other", :old=>"Mnky", :when=>2017-08-24 11:17:58 -0400}]
t.name
#=> "Other"

关于ruby - 有什么方法可以检测 Ruby 中的属性变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45853128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com