我已经定义了几个虚拟属性,定义了setter和getters方法:
class Post < ActiveRecord::Base
def shared_to_all
# evaluates some expression of the attribute privacy
end
def shared_to_friends
# evaluates some other expression of the attribute privacy
end
def shared_to_all=(bool)
# write_attribute( :privacy, ... )
end
def shared_to_friends=(bool)
# write_attribute( :privacy, ... )
end
end
到目前为止一直很好,但我也希望使用符号使这个虚拟属性可用,所以我可以做@post= Post.first; @post[:shared_to_all]= true
[编辑:]
Ruby方法是覆盖[]
和[]=
运算符,如:
def [](shared_to_all)
shared_to_all
end
def []=(shared_to_all, bool)
self.shared_to_all= (bool)
end
但这似乎打破了Rails关系方法(has_one
- has_many
- belongs_to
- has_and_belongs_to_many
指令带来的方法):现在Post.first.author => nil
和Author.first.posts => []
答案 0 :(得分:0)
似乎应该这样做:
def [](attr)
attr
end
def []=(attr, value)
self.attr = value
end