I'm trying to integrate Redis into a Rails app to replace "has_many through" relations. I'd like to do that seamlessly so we don't have to change the code through out the app. My idea is to override different methods of some class attributes (the followers attribute of the class Speaker for example) to be able to create custom behavior when using them: Here are behaviors I'd like to get to:
s = Speaker.new
s.followers # calls custom getter and returns [User1, User2]
s.followers << User.create
s.followers # calls custom getter and returns [User1, User2, User3]
Here is my idea inspired by Overriding instance variable array's operators in Ruby
class Speaker < ActiveRecord::Base
attr_accessor :followers
def initialize
super
@followers = []
class << @followers
def <<(u)
puts "setter #{u.id}"
$redis.set "speaker#{self.id}followers", u.id
super(u.id)
end
end
end
def followers
puts "getter"
user_ids = $redis.get "speaker#{self.id}followers"
User.find_all user_ids
end
end
The problem is that the implementation of the followers getter override the implementation of "def <<(val)"
if the getter "def followers" is not defined:
s.followers
# []
s.followers << User.create
# "setter 1"
# [1]
s.followers
# [1]
s.followers << User.create
# "setter 2"
# [1, 2]
s.followers
# [1, 2]
if the getter "def attendees" is defined:
s.followers << User.create
# ["My", "Custom", "Array", User1]
s.followers
# ["My", "Custom", "Array"]
s.followers << User.create
# ["My", "Custom", "Array", User2]
s.followers
# ["My", "Custom", "Array"]
How could I get the getter and the setter "<<" to work together?