在Rails中定义虚拟属性并使其可用作符号

时间:2013-05-11 17:46:17

标签: ruby-on-rails symbols getter-setter virtual-attribute

我已经定义了几个虚拟属性,定义了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 => nilAuthor.first.posts => []

1 个答案:

答案 0 :(得分:0)

似乎应该这样做:

def [](attr)
  attr
end
def []=(attr, value)
  self.attr = value
end