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

标签 ruby

我有这个代码:

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/

相关文章:

ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension

ruby-on-rails - Ruby on Rails URL 格式

ruby - 无法在 Ruby 中使用 Gosu 打印文本(崩溃)

ruby-on-rails - minitest: 未定义的方法 `get'

ruby-on-rails - 回到 rails 的最快方法

ruby-on-rails - 针对外部 API 验证 Rails 模型

ruby-on-rails - RefineryCMS 管理功能

java - 为什么之前运行的代码中会出现错误 "Uninitialized constant DriverManager"?

ruby-on-rails - Rails 将多个表导出到 csv

ruby - 在 Jekyll 中使用 Live Reload