ActiveRedis
Installation
Add this line to your application's Gemfile:
gem 'active_redis_orm'
And then execute:
$ bundle
Or install it yourself as:
$ gem install active_redis_orm
Usage
In an initializer, make sure that you're using the correct connection:
ActiveRedis.redis = Redis.new(connection_details)
Creating an ActiveRedis class looks like a combination of ActiveRecord and Mongoid:
class User < ActiveRedis::Base
field :username, finder_field: true
field :name
field :birthday, type: :date
field :age, type: :integer, default: lambda{|user| user.age_from_birthday}
field :things, type: :set
end
Declaring fields is similar to Mongoid - you declare the field, and its type (the default is string). We use symbols for type, unlike Mongoid which uses the data type's class.
Available types are: :string, :set, :sorted_set, :list, :hash, :float, :integer (or :int), :counter, :boolean, :date, :time (or :datetime, :timestamp).
You can declare a default value with either a value or a lambda.
Finder Fields
When you want to be able to find an object by something other than its ID, you can define an index by stating a field to be a finder_field. This will allow you to do this:
User.create(username: "some_guy")
User.find_by_username("some_guy") #=> our user
Redis Data Structures
Using hashes, sets, sorted sets and lists is simple-ish.
Hash simply acts like a hash
Sets and Lists act like any ruby array
Sorted sets' getters act as an array, but setters are hash-like, where the hash key is the value and hash value is the score. Yes, it's a bit confusing.
class User < ActiveRedis::Base
field :foo, type: :sorted_set
end
user = User.new
user.foo["value2"] = 1
user.foo["value1"] = 0
user.save
user.foo #=> ["value1", "value2"]
Callbacks and Validations
Callbacks and validations work just like in Mongoid or ActiveRecord
class Messages < ActiveRedis::Base
include ActiveRedis::Timestamps
field :text
field :user_id
validates :text, presence: true, length: {maximum: 256}
validates :user_id, presence: true
after_create :do_something
def do_something
#this gets called after create
end
end
= Message.new(text: "I am new text")
.save #=> false
.errors. #=> {:user_id=>["can't be blank"]}
available callbacks are before/after/around for create/update/save
available validations are any validations which come with ActiveModel (we're still missing the uniqueness validation, as it's a problem in redis, but it'll happen)
Contributing
- Fork it ( http://github.com/
/active_redis_orm/fork ) - Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request