{"id":13463049,"url":"https://github.com/nateware/redis-objects","last_synced_at":"2025-04-29T18:35:10.163Z","repository":{"id":720270,"uuid":"367591","full_name":"nateware/redis-objects","owner":"nateware","description":"Map Redis types directly to Ruby objects","archived":false,"fork":false,"pushed_at":"2023-03-30T19:57:08.000Z","size":782,"stargazers_count":2087,"open_issues_count":16,"forks_count":229,"subscribers_count":39,"default_branch":"master","last_synced_at":"2025-04-10T00:09:40.787Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"artistic-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nateware.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.rdoc","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2009-11-10T14:32:02.000Z","updated_at":"2025-03-31T14:33:17.000Z","dependencies_parsed_at":"2023-07-05T15:16:33.728Z","dependency_job_id":null,"html_url":"https://github.com/nateware/redis-objects","commit_stats":{"total_commits":451,"total_committers":99,"mean_commits":4.555555555555555,"dds":0.7206208425720622,"last_synced_commit":"8ab0b424f0db008873d6bef098565a9a5f6f7b20"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nateware%2Fredis-objects","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nateware%2Fredis-objects/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nateware%2Fredis-objects/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nateware%2Fredis-objects/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nateware","download_url":"https://codeload.github.com/nateware/redis-objects/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251560921,"owners_count":21609288,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:44.943Z","updated_at":"2025-04-29T18:35:10.145Z","avatar_url":"https://github.com/nateware.png","language":"Ruby","readme":"Redis::Objects - Map Redis types directly to Ruby objects\n=========================================================\n\n[![Build Status](https://app.travis-ci.com/nateware/redis-objects.svg?branch=master)](https://travis-ci.com/github/nateware/redis-objects)\n[![Code Coverage](https://codecov.io/gh/nateware/redis-objects/branch/master/graph/badge.svg)](https://codecov.io/gh/nateware/redis-objects)\n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=MJF7JU5M7F8VL)\n\nImportant 2.0 changes\n=====================\nRedis::Objects 2.0 introduces several important backwards incompatible changes.\nCurrently 2.0 can be installed with `gem install redis-objects --pre` or by listing it\nexplicitly in your Gemfile:\n~~~ruby\n# Gemfile\ngem 'redis-objects', '\u003e= 2.0.0.beta'\n~~~\nYou're encouraged to try it out in test code (not production) to ensure it works for you.\nOfficial release is expected later in 2023.\n\nKey Naming Changes\n------------------\nThe internal key naming scheme has changed for `Nested::Class::Namespaces` to fix a longstanding bug.\n**This means your existing data in Redis will not be accessible until you call `migrate_redis_legacy_keys`.**\n\nTo fix this (only needed once), create a script like this:\n\n~~~ruby\nclass YouClassNameHere \u003c ActiveRecord::Base\n  include Redis::Objects\n  # ... your relevant definitions here ...\nend\n\nYourClassName.migrate_redis_legacy_keys\n~~~\n\nThen, you need to find a time when you can temporarily pause writes to your redis server\nso that you can run that script. It uses `redis.scan` internally so it should be able to\nhandle a high number of keys. For large data sets, it could take a while.\n\nFor more details on the issue and fix refer to [#213](https://github.com/nateware/redis-objects/issues/231).\n\nRenaming of `lock` Method\n-------------------------\nThe `lock` method that collided with `ActiveRecord::Base` has been renamed `redis_lock`.\nThis means your classes need to be updated to call `redis_lock` instead:\n\n~~~ruby\nclass YouClassNameHere \u003c ActiveRecord::Base\n  include Redis::Objects\n  redis_lock :mylock  # formerly just \"lock\"\nend \n~~~\n\nFor more details on the issue and fix refer to [#196](https://github.com/nateware/redis-objects/issues/196).\n\nOverview\n--------\nThis is **not** an ORM. People that are wrapping ORM’s around Redis are missing the point.\n\nThe killer feature of Redis is that it allows you to perform _atomic_ operations\non _individual_ data structures, like counters, lists, and sets.  The **atomic** part is HUGE.\nUsing an ORM wrapper that retrieves a \"record\", updates values, then sends those values back,\n_removes_ the atomicity, and thus the major advantage of Redis.  Just use MySQL, k?\n\nThis gem provides a Rubyish interface to Redis, by mapping [Redis data types](http://redis.io/commands)\nto Ruby objects, via a thin layer over the `redis` gem.  It offers several advantages\nover the lower-level redis-rb API:\n\n1. Easy to integrate directly with existing ORMs - ActiveRecord, DataMapper, etc.  Add counters to your model!\n2. Complex data structures are automatically Marshaled (if you set :marshal =\u003e true)\n3. Integers are returned as integers, rather than '17'\n4. Higher-level types are provided, such as Locks, that wrap multiple calls\n\nThis gem originally arose out of a need for high-concurrency atomic operations;\nfor a fun rant on the topic, see [An Atomic Rant](http://nateware.com/2010/02/18/an-atomic-rant),\nor scroll down to [Atomic Counters and Locks](#atomicity) in this README.\n\nThere are two ways to use Redis::Objects, either as an include in a model class (to\ntightly integrate with ORMs or other classes), or standalone by using classes such\nas `Redis::List` and `Redis::SortedSet`.\n\nInstallation and Setup\n----------------------\nAdd it to your Gemfile as:\n\n~~~ruby\ngem 'redis-objects'\n~~~\n\nRedis::Objects needs a handle created by `Redis.new` or a [ConnectionPool](https://github.com/mperham/connection_pool):\n\nThe recommended approach is to use a `ConnectionPool` since this guarantees that most timeouts in the `redis` client\ndo not pollute your existing connection. However, you need to make sure that both `:timeout` and `:size` are set appropriately\nin a multithreaded environment.\n~~~ruby\nrequire 'connection_pool'\nRedis::Objects.redis = ConnectionPool.new(size: 5, timeout: 5) { Redis.new(:host =\u003e '127.0.0.1', :port =\u003e 6379) }\n~~~\n\nRedis::Objects can also default to `Redis.current` if `Redis::Objects.redis` is not set.\n~~~ruby\nRedis.current = Redis.new(:host =\u003e '127.0.0.1', :port =\u003e 6379)\n~~~\n\n(If you're on Rails, `config/initializers/redis.rb` is a good place for this.)\nRemember you can use Redis::Objects in any Ruby code.  There are **no** dependencies\non Rails.  Standalone, Sinatra, Resque - no problem.\n\nAlternatively, you can set the `redis` handle directly:\n\n~~~ruby\nRedis::Objects.redis = Redis.new(...)\n~~~\n\nFinally, you can even set different handles for different classes:\n\n~~~ruby\nclass User\n  include Redis::Objects\nend\nclass Post\n  include Redis::Objects\nend\n\n# you can also use a ConnectionPool here as well\nUser.redis = Redis.new(:host =\u003e '1.2.3.4')\nPost.redis = Redis.new(:host =\u003e '5.6.7.8')\n~~~\n\nAs of `0.7.0`, `redis-objects` now autoloads the appropriate `Redis::Whatever`\nclasses on demand.  Previous strategies of individually requiring `redis/list`\nor `redis/set` are no longer required.\n\nOption 1: Model Class Include\n=============================\nIncluding Redis::Objects in a model class makes it trivial to integrate Redis types\nwith an existing ActiveRecord, DataMapper, Mongoid, or similar class.  **Redis::Objects\nwill work with _any_ class that provides an `id` method that returns a unique value.**\nRedis::Objects automatically creates keys that are unique to each object, in the format:\n\n    model_name:id:field_name\n\nFor illustration purposes, consider this stub class:\n\n~~~ruby\nclass User\n  include Redis::Objects\n  counter :my_posts\n  def id\n    1\n  end\nend\n\nuser = User.new\nuser.id  # 1\nuser.my_posts.increment\nuser.my_posts.increment\nuser.my_posts.increment\nputs user.my_posts.value # 3\nuser.my_posts.reset\nputs user.my_posts.value # 0\nuser.my_posts.reset 5\nputs user.my_posts.value # 5\n~~~\n\nHere's an example that integrates several data types with an ActiveRecord model:\n\n~~~ruby\nclass Team \u003c ActiveRecord::Base\n  include Redis::Objects\n\n  redis_lock :trade_players, :expiration =\u003e 15  # sec\n  value :at_bat\n  counter :hits\n  counter :runs\n  counter :outs\n  counter :inning, :start =\u003e 1\n  list :on_base\n  list :coaches, :marshal =\u003e true\n  set  :outfielders\n  hash_key :pitchers_faced  # \"hash\" is taken by Ruby\n  sorted_set :rank, :global =\u003e true\nend\n~~~\n\nFamiliar Ruby array operations Just Work (TM):\n\n~~~ruby\n@team = Team.find_by_name('New York Yankees')\n@team.on_base \u003c\u003c 'player1'\n@team.on_base \u003c\u003c 'player2'\n@team.on_base \u003c\u003c 'player3'\n@team.on_base    # ['player1', 'player2', 'player3']\n@team.on_base.pop\n@team.on_base.shift\n@team.on_base.length  # 1\n@team.on_base.delete('player2')\n@team.on_base = ['player1', 'player2']  # ['player1', 'player2']\n~~~\n\nSets work too:\n\n~~~ruby\n@team.outfielders \u003c\u003c 'outfielder1'\n@team.outfielders \u003c\u003c 'outfielder2'\n@team.outfielders \u003c\u003c 'outfielder1'   # dup ignored\n@team.outfielders  # ['outfielder1', 'outfielder2']\n@team.outfielders.each do |player|\n  puts player\nend\nplayer = @team.outfielders.detect{|of| of == 'outfielder2'}\n@team.outfielders = ['outfielder1', 'outfielder3']  # ['outfielder1', 'outfielder3']\n~~~\n\nHashes work too:\n\n~~~ruby\n@team.pitchers_faced['player1'] = 'pitcher2'\n@team.pitchers_faced['player2'] = 'pitcher1'\n@team.pitchers_faced = { 'player1' =\u003e 'pitcher2', 'player2' =\u003e 'pitcher1' }\n~~~\n\nAnd you can do unions and intersections between objects (kinda cool):\n\n~~~ruby\n@team1.outfielders | @team2.outfielders   # outfielders on both teams\n@team1.outfielders \u0026 @team2.outfielders   # in baseball, should be empty :-)\n~~~\n\nCounters can be atomically incremented/decremented (but not assigned):\n\n~~~ruby\n@team.hits.increment  # or incr\n@team.hits.decrement  # or decr\n@team.hits.incr(3)    # add 3\n@team.runs = 4        # exception\n~~~\n\nDefining a different method as the `id` field is easy\n\n~~~ruby\nclass User\n  include Redis::Objects\n  redis_id_field :uid\n  counter :my_posts\nend\n\nuser.uid                # 195137a1bdea4473\nuser.my_posts.increment # 1\n~~~\n\nFinally, for free, you get a `redis` method that points directly to a Redis connection:\n\n~~~ruby\nTeam.redis.get('somekey')\n@team = Team.new\n@team.redis.get('somekey')\n@team.redis.smembers('someset')\n~~~\n\nYou can use the `redis` handle to directly call any [Redis API command](http://redis.io/commands).\n\nOption 2: Standalone Usage\n===========================\nThere is a Ruby class that maps to each Redis type, with methods for each\n[Redis API command](http://redis.io/commands).\nNote that calling `new` does not imply it's actually a \"new\" value - it just\ncreates a mapping between that Ruby object and the corresponding Redis data\nstructure, which may already exist on the `redis-server`.\n\nCounters\n--------\nThe `counter_name` is the key stored in Redis.\n\n~~~ruby\n@counter = Redis::Counter.new('counter_name')\n@counter.increment  # or incr\n@counter.decrement  # or decr\n@counter.increment(3)\nputs @counter.value\n~~~\n\nThis gem provides a clean way to do atomic blocks as well:\n\n~~~ruby\n@counter.increment do |val|\n  raise \"Full\" if val \u003e MAX_VAL  # rewind counter\nend\n~~~\n\nSee the section on [Atomic Counters and Locks](#atomicity) for cool uses of atomic counter blocks.\n\nLocks\n-----\nA convenience class that wraps the pattern of [using setnx to perform locking](http://redis.io/commands/setnx).\n\n~~~ruby\n@lock = Redis::Lock.new('serialize_stuff', :expiration =\u003e 15, :timeout =\u003e 0.1)\n@lock.lock do\n  # do work\nend\n~~~\n\nThis can be especially useful if you're running batch jobs spread across multiple hosts.\n\nValues\n------\nSimple values are easy as well:\n\n~~~ruby\n@value = Redis::Value.new('value_name')\n@value.value = 'a'\n@value.delete\n~~~\n\nComplex data is no problem with :marshal =\u003e true:\n\n~~~ruby\n@account = Account.create!(params[:account])\n@newest  = Redis::Value.new('newest_account', :marshal =\u003e true)\n@newest.value = @account.attributes\nputs @newest.value['username']\n~~~\n\nCompress data to save memory usage on Redis with :compress =\u003e true:\n\n~~~ruby\n@account = Account.create!(params[:account])\n@marshaled_value = Redis::Value.new('marshaled', :marshal =\u003e true, :compress =\u003e true)\n@marshaled_value.value = @account.attributes\n@unmarshaled_value = Redis::Value.new('unmarshaled', :compress =\u003e true)\n@unmarshaled_value = 'Really Long String'\nputs @marshaled_value.value['username']\nputs @unmarshaled_value.value\n~~~\n\nLists\n-----\nLists work just like Ruby arrays:\n\n~~~ruby\n@list = Redis::List.new('list_name')\n@list \u003c\u003c 'a'\n@list \u003c\u003c 'b'\n@list.include? 'c'   # false\n@list.values  # ['a','b']\n@list \u003c\u003c 'c'\n@list.delete('c')\n@list[0]\n@list[0,1]\n@list[0..1]\n@list.shift\n@list.pop\n@list.clear\n# etc\n~~~\n\nYou can bound the size of the list to only hold N elements like so:\n\n~~~ruby\n# Only holds 10 elements, throws out old ones when you reach :maxlength.\n@list = Redis::List.new('list_name', :maxlength =\u003e 10)\n~~~\n\nComplex data types are serialized with :marshal =\u003e true:\n\n~~~ruby\n@list = Redis::List.new('list_name', :marshal =\u003e true)\n@list \u003c\u003c {:name =\u003e \"Nate\", :city =\u003e \"San Diego\"}\n@list \u003c\u003c {:name =\u003e \"Peter\", :city =\u003e \"Oceanside\"}\n@list.each do |el|\n  puts \"#{el[:name]} lives in #{el[:city]}\"\nend\n~~~\n\nNote: If you run into issues, with Marshal errors, refer to the fix in [Issue #176](https://github.com/nateware/redis-objects/issues/176).\n\nHashes\n------\nHashes work like a Ruby [Hash](http://ruby-doc.org/core/classes/Hash.html), with\na few Redis-specific additions.  (The class name is \"HashKey\" not just \"Hash\", due to\nconflicts with the Ruby core Hash class in other gems.)\n\n~~~ruby\n@hash = Redis::HashKey.new('hash_name')\n@hash['a'] = 1\n@hash['b'] = 2\n@hash.each do |k,v|\n  puts \"#{k} = #{v}\"\nend\n@hash['c'] = 3\nputs @hash.all  # {\"a\"=\u003e\"1\",\"b\"=\u003e\"2\",\"c\"=\u003e\"3\"}\n@hash.clear\n~~~\n\nRedis also adds incrementing and bulk operations:\n\n~~~ruby\n@hash.incr('c', 6)  # 9\n@hash.bulk_set('d' =\u003e 5, 'e' =\u003e 6)\n@hash.bulk_get('d','e')  # \"5\", \"6\"\n~~~\n\nRemember that numbers become strings in Redis.  Unlike with other Redis data types,\n`redis-objects` can't guess at your data type in this situation, since you may\nactually mean to store \"1.5\".\n\nSets\n----\nSets work like the Ruby [Set](http://ruby-doc.org/core/classes/Set.html) class.\nThey are unordered, but guarantee uniqueness of members.\n\n~~~ruby\n@set = Redis::Set.new('set_name')\n@set \u003c\u003c 'a'\n@set \u003c\u003c 'b'\n@set \u003c\u003c 'a'  # dup ignored\n@set.member? 'c'      # false\n@set.members          # ['a','b']\n@set.members.reverse  # ['b','a']\n@set.each do |member|\n  puts member\nend\n@set.clear\n# etc\n~~~\n\nYou can perform Redis intersections/unions/diffs easily:\n\n~~~ruby\n@set1 = Redis::Set.new('set1')\n@set2 = Redis::Set.new('set2')\n@set3 = Redis::Set.new('set3')\nmembers = @set1 \u0026 @set2   # intersection\nmembers = @set1 | @set2   # union\nmembers = @set1 + @set2   # union\nmembers = @set1 ^ @set2   # difference\nmembers = @set1 - @set2   # difference\nmembers = @set1.intersection(@set2, @set3)  # multiple\nmembers = @set1.union(@set2, @set3)         # multiple\nmembers = @set1.difference(@set2, @set3)    # multiple\n~~~\n\nOr store them in Redis:\n\n~~~ruby\n@set1.interstore('intername', @set2, @set3)\nmembers = @set1.redis.get('intername')\n@set1.unionstore('unionname', @set2, @set3)\nmembers = @set1.redis.get('unionname')\n@set1.diffstore('diffname', @set2, @set3)\nmembers = @set1.redis.get('diffname')\n~~~\n\nAnd use complex data types too, with :marshal =\u003e true:\n\n~~~ruby\n@set1 = Redis::Set.new('set1', :marshal =\u003e true)\n@set2 = Redis::Set.new('set2', :marshal =\u003e true)\n@set1 \u003c\u003c {:name =\u003e \"Nate\",  :city =\u003e \"San Diego\"}\n@set1 \u003c\u003c {:name =\u003e \"Peter\", :city =\u003e \"Oceanside\"}\n@set2 \u003c\u003c {:name =\u003e \"Nate\",  :city =\u003e \"San Diego\"}\n@set2 \u003c\u003c {:name =\u003e \"Jeff\",  :city =\u003e \"Del Mar\"}\n\n@set1 \u0026 @set2  # Nate\n@set1 - @set2  # Peter\n@set1 | @set2  # all 3 people\n~~~\n\nSorted Sets\n-----------\nDue to their unique properties, Sorted Sets work like a hybrid between\na Hash and an Array.  You assign like a Hash, but retrieve like an Array:\n\n~~~ruby\n@sorted_set = Redis::SortedSet.new('number_of_posts')\n@sorted_set['Nate']  = 15\n@sorted_set['Peter'] = 75\n@sorted_set['Jeff']  = 24\n\n# Array access to get sorted order\n@sorted_set[0..2]           # =\u003e [\"Nate\", \"Jeff\", \"Peter\"]\n@sorted_set[0,2]            # =\u003e [\"Nate\", \"Jeff\"]\n\n@sorted_set['Peter']        # =\u003e 75\n@sorted_set['Jeff']         # =\u003e 24\n@sorted_set.score('Jeff')   # same thing (24)\n\n@sorted_set.rank('Peter')   # =\u003e 2\n@sorted_set.rank('Jeff')    # =\u003e 1\n\n@sorted_set.first           # =\u003e \"Nate\"\n@sorted_set.last            # =\u003e \"Peter\"\n@sorted_set.revrange(0,2)   # =\u003e [\"Peter\", \"Jeff\", \"Nate\"]\n\n@sorted_set['Newbie'] = 1\n@sorted_set.members         # =\u003e [\"Newbie\", \"Nate\", \"Jeff\", \"Peter\"]\n@sorted_set.members.reverse # =\u003e [\"Peter\", \"Jeff\", \"Nate\", \"Newbie\"]\n\n@sorted_set.rangebyscore(10, 100, :limit =\u003e 2)   # =\u003e [\"Nate\", \"Jeff\"]\n@sorted_set.members(:with_scores =\u003e true)        # =\u003e [[\"Newbie\", 1], [\"Nate\", 16], [\"Jeff\", 28], [\"Peter\", 76]]\n\n# atomic increment\n@sorted_set.increment('Nate')\n@sorted_set.incr('Peter')   # shorthand\n@sorted_set.incr('Jeff', 4)\n~~~\n\nThe other Redis Sorted Set commands are supported as well; see [Sorted Sets API](http://redis.io/commands#sorted_set).\n\n\u003ca name=\"atomicity\"\u003e\u003c/a\u003e\nAtomic Counters and Locks\n-------------------------\nYou are probably not handling atomicity correctly in your app.  For a fun rant\non the topic, see [An Atomic Rant](http://nateware.com/an-atomic-rant.html).\n\nAtomic counters are a good way to handle concurrency:\n\n~~~ruby\n@team = Team.find(1)\nif @team.drafted_players.increment \u003c= @team.max_players\n  # do stuff\n  @team.team_players.create!(:player_id =\u003e 221)\n  @team.active_players.increment\nelse\n  # reset counter state\n  @team.drafted_players.decrement\nend\n~~~\n\nAn _atomic block_ gives you a cleaner way to do the above. Exceptions or returning nil\nwill rewind the counter back to its previous state:\n\n~~~ruby\n@team.drafted_players.increment do |val|\n  raise Team::TeamFullError if val \u003e @team.max_players  # rewind\n  @team.team_players.create!(:player_id =\u003e 221)\n  @team.active_players.increment\nend\n~~~\n\nHere's a similar approach, using an if block (failure rewinds counter):\n\n~~~ruby\n@team.drafted_players.increment do |val|\n  if val \u003c= @team.max_players\n    @team.team_players.create!(:player_id =\u003e 221)\n    @team.active_players.increment\n  end\nend\n~~~\n\nClass methods work too, using the familiar ActiveRecord counter syntax:\n\n~~~ruby\nTeam.increment_counter :drafted_players, team_id\nTeam.decrement_counter :drafted_players, team_id, 2\nTeam.increment_counter :total_online_players  # no ID on global counter\n~~~\n\nClass-level atomic blocks can also be used.  This may save a DB fetch, if you have\na record ID and don't need any other attributes from the DB table:\n\n~~~ruby\nTeam.increment_counter(:drafted_players, team_id) do |val|\n  TeamPitcher.create!(:team_id =\u003e team_id, :pitcher_id =\u003e 181)\n  Team.increment_counter(:active_players, team_id)\nend\n~~~\n\n### Locks ###\n\nLocks work similarly. On completion or exception the lock is released:\n\n~~~ruby\nclass Team \u003c ActiveRecord::Base\n  redis_lock :reorder # declare a lock\nend\n\n@team.reorder_lock.lock do\n  @team.reorder_all_players\nend\n~~~\n\nClass-level lock (same concept)\n\n~~~ruby\nTeam.obtain_lock(:reorder, team_id) do\n  Team.reorder_all_players(team_id)\nend\n~~~\n\nLock expiration.  Sometimes you want to make sure your locks are cleaned up should\nthe unthinkable happen (server failure).  You can set lock expirations to handle\nthis.  Expired locks are released by the next process to attempt lock.  Just\nmake sure you expiration value is sufficiently large compared to your expected\nlock time.\n\n~~~ruby\nclass Team \u003c ActiveRecord::Base\n  redis_lock :reorder, :expiration =\u003e 15.minutes\nend\n~~~\n\nKeep in mind that true locks serialize your entire application at that point.  As\nsuch, atomic counters are strongly preferred.\n\n### Expiration ###\n\nUse :expiration and :expireat options to set default expiration.\n\n~~~ruby\nvalue :value_with_expiration, :expiration =\u003e 1.hour\nvalue :value_with_expireat, :expireat =\u003e lambda { Time.now + 1.hour }\n~~~\n\n:warning: In the above example, `expiration` is evaluated at class load time.\nIn this example, it will be one hour after loading the class, not after one hour\nafter setting a value. If you want to expire one hour after setting the value,\nplease use `:expireat` with `lambda`.\n\nCustom serialization\n--------------------\nYou can customize how values are serialized by setting `serializer: CustomSerializer`.\nThe default is `Marshal` from the standard lib, but it can be anything that responds to `dump` and\n`load`. `JSON` and `YAML` are popular options.\n\nIf you need to pass extra arguments to `dump` or `load`, you can set\n`marshal_dump_args: { foo: 'bar' }` and `marshal_load_args: { foo: 'bar' }` respectively.\n\n~~~ruby\nclass CustomSerializer\n  def self.dump(value)\n    # custom code for serializing\n  end\n\n  def self.load(value)\n    # custom code for deserializing\n  end\nend\n\n@account = Account.create!(params[:account])\n@newest  = Redis::Value.new('custom_serializer', marshal: true, serializer: CustomSerializer)\n@newest.value = @account.attributes\n~~~\n\nAuthor\n=======\nCopyright (c) 2009-2022 [Nate Wiger](http://nateware.com).  All Rights Reserved.\nReleased under the [Artistic License](http://www.opensource.org/licenses/artistic-license-2.0.php).\n","funding_links":["https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=MJF7JU5M7F8VL"],"categories":["Data Persistence","Ruby","ORM/ODM","Higher level libraries and tools"],"sub_categories":["Redis Clients"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnateware%2Fredis-objects","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnateware%2Fredis-objects","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnateware%2Fredis-objects/lists"}