Search code examples
rubyredisohm

How do you push an element onto a list dynamically in Redis/Ohm?


This is a follow-up to this question: Setting a dynamic field in Ohm / Redis

I'm unable to find the method that I can use with the send() method, to dynamically be able to add an object to an unknown list. I tried adding this method to the Ohm::Model class:

def add_to_list(name, obj)
    send((name.to_s + '<<').to_sym, obj)
end
h.add_to_list(:player_ids, OhmSeat.create(seat_number: 5, value: 6))

But I get

undefined method `player_ids<<'

There is a rpush method, but I can't seem to call it directly. and this doesn't work:

h.player_ids.rpush(OhmSeat.create(seat_number: 5, value: 6)) 

Solution

  • As @Andrew Grimm mentioned, you should do:

    def add_to_list(name, obj)
      send(name) << obj
    end
    

    or just do:

    h.player_ids << OhmSeat.create(...)