I've defined a couple of virtual attributes, defining both the setter and the getters methods:
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
So far so good, but I want also to make this virtual attributes available using symbols, so I can do something like @post= Post.first; @post[:shared_to_all]= true
[Edit:]
A Ruby approach would be to override []
and []=
operators, like in:
def [](shared_to_all)
shared_to_all
end
def []=(shared_to_all, bool)
self.shared_to_all= (bool)
end
But this seems to break Rails relationship methods (those brought by has_one
- has_many
- belongs_to
- has_and_belongs_to_many
directives): e.g. now Post.first.author => nil
and Author.first.posts => []