受到 meteor 的启发,做了一个 autodeps: https://github.com/femto/autodeps
现在 reactive programming 这么热,做一个 reactive programming (reactive programming 意思就是 a=b+c, 传统 imperative programming 就是一次赋值,而 reactive programming a 就等于 b+c,哪怕 b 或者 c 值 change,也会 propagate 到 a
对于 Persistent 部分, 比如赞,一个用户赞另外一个用户,
class Laud
include MongoMapper::Document
include Autodeps::Persistency #这里添加对Autodeps::Persistency 的依赖
key :user_id, Integer, :required => true
key :user_name, String
depend_on "User", :value_mapping => {:name => :user_name} #默认可以省略 :key_mapping=> {:id=>:user_id}
key :dest_user_id, Integer, :required => true
key :dest_user_name, String
depend_on "User", :key_mapping => {:id => :dest_user_id}, :value_mapping => {:name => :dest_user_name}
timestamps!
ensure_index([[:user_id,1],[:dest_user_id,1]])
end
即可, 然后 user.save 的时候,
user=User.first
user.name="123"
user.save ==>#这里会propagate change到Laud
在 development 环境下,有可能 User 加载了而 Laud 完全没加载,可以在后面写对 Laud 的引用强迫 load Laud 文件
class User
#some attributes
end
Laud
##这样 @huacnlee这样 Ruby-China UserName 的 update 就简单多了吧?
##另外做了一个ReactiveData: a=b+c,相当于 b,c 用 ReactiveData,则 a 会自动知道 b,c 的变化, 可以参看 autodeps_test.rb:
def test_invalidate
a = 3
b = nil
computation = Autodeps.autorun do |computation|
b = a
end
assert_equal b,a
a = 5
computation.invalidate
assert_equal b,a
end
def test_reactive_integer
a = Autodeps::ReactiveData.new(3)
b = nil
computation = Autodeps.autorun do |computation|
b = a.value
end
assert_equal b,3
a.change_to 5
assert_equal b,5
end
def test_reactive_integer_add
a = Autodeps::ReactiveData.new(3)
b = Autodeps::ReactiveData.new(5)
c = nil
computation = Autodeps.autorun do |computation|
c = a.value + b.value
end
assert_equal c,8
a.change_to 5
assert_equal c,10
b.change_to 15
assert_equal c,20
end