Hacker News new | ask | show | jobs
by geocar 4257 days ago
The view automatically gets updated whenever a gets updated. Every time you change a (directly or indirectly), then c will automatically get updated.

Doing this generally in Ruby I think is impossible, but you might be able to get close if all your objects are based on ActiveModel::Dirty

1 comments

> Doing this generally in Ruby I think is impossible

Not so much. At least with views over most Enumerables, its quite possible in Ruby -- that's the whole reason that Enumerable::Lazy exists.

The existing File class doesn't quite support it because of the way its iterators are implemented (particularly, they are one way) but the class is easily extended to allow it, e.g.:

  class RewindFile < File
    def each
      rewind
      each_char {|x| yield x}
    end
  end
 
Then you can create a synced view that has the character positions of the newlines in a file like this:

  a = RewindFile.new "myfile.txt"
  c = a.lazy.each
            .with_index
            .find_all {|x,_| x=="\n"}
            .map {|_,y| y}
If I go `a=whatever` or `a[42]=whatever`, then `c` will not get updated if I have already consumed those values; I still need to "reset" c every time I update a.