💾 Archived View for gem.graypegg.com › gor › persistents captured on 2023-01-29 at 02:46:06. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
are my half-baked idea around how to handle 'view models' in a way that doesn't require too much over head. You can think of it as a way to handle one 'atom' of data. It has hooks to handle when connections happen, and the ability to be imported into controllers to use or update that value.
There's some utility methods included in the Persistent class to write to a csv file, but you could just as easily use volatile memory and store everything in instance vars if you want.
You can make a persistent by just adding a new file in /app/persistent. It will be loaded automatically. A simple persistent looks like the following:
╭─────────┤ app/persistents/hit_counter.rb ├─╮ class HitCounter < Persistent def on_connection(_connection) @count = get('hitcount').to_i || 0 @count += 1 set('hitcount', @count) end def draw_counter "#{@count} hits" end end ╰────────────────────────────────────────────╯
This can then be used in a controller, using the 'Controller#use_persistent' method, which gets you the server's current instance of that persistent as in the following toy example.
╭───────────────────────┤ app/home_page_controller.rb ├─╮ class HomePageController < Controller def get respond_with <<~TEXT # Gray's space #{use_persistent(:HitCounter).draw_counter} TEXT end end ╰───────────────────────────────────────────────────────╯
which renders our hit counter on screen, like the following
╭─────────┤ Output ├─╮ # Gray's space 2 hits ╰────────────────────╯
def on_connection(conn); end
Shadow this method in your class that extends Persistent to have a hook when a new connection is created. The current connection is passed.
def on_init(); end
Shadow this method in your class that extends Persistent to have a hook when the server first starts up.
get(key)
Gets a value from the persistent.csv key-value store. The key must be a string. The value returned will be either a string or nil.
set(key, value)
Write a value to the persistent.csv key-value store. The key must be a string. The value will be .to_s'd before storing it. There's nothing stopping you from storing JSON if you'd like.