0

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 => []

Claudio Floreani
  • 2,441
  • 28
  • 34

1 Answers1

0

Seems like this should do it:

def [](attr)
  attr
end
def []=(attr, value)
  self.attr = value
end
cpuguy83
  • 5,794
  • 4
  • 18
  • 24
  • Redefining `[]` and `[]=` operators seems to break relationship methods (those available via has_one - has_many - belongs_to - has_and_belongs_to_many directives): e.g. now `Post.first.author => nil` `Author.first.posts => []` – Claudio Floreani May 12 '13 at 18:06