Categoryz3¶ ↑
<img src=“https://secure.travis-ci.org/tscolari/categoryz3.png” /> <img src=“https://codeclimate.com/github/tscolari/categoryz3.png” />
__Version 0.9+ is rails4 compatible__
Simple categorization to ActiveRecord models.
Works like a simple tagging system, but instead of tags it has categories, and categories may have an ilimited level of subcategories.
Fetches items in any level of subcategories with a single join.
Motivation¶ ↑
genres_category = Categoryz3::Category.create(name: 'genres') horror_category = Categoryz3::Category.create(name: 'horror', parent: genres_category) cult_horror_category = Categoryz3::Category.create(name: 'horror', parent: horror_category) action_category = Categoryz3::Category.create(name: 'horror', parent: genres_category) horror_movie = Movie.find(1) horror_movie.categories << cult_horror_category horror_movie.categories #=> [cult_horror_category] action_movie = Movie.find(2) action_movie.categories << action_category Movie.inside_category(genres_category).all #=> [horror_movie, action_movie] Movie.inside_category(horror_category).all #=> [horror_movie] Movie.inside_category(cult_horror_category).all #=> [horror_movie] horror_category.path #=> [movie_category, horror_category]
Installation¶ ↑
Insert the gem in your Gemfile:
gem 'categoryz3'
Generate and run the migrations:
rails g categoryz3:migrations rake db:migrate
Include the categorizable module in the models you want to categorize:
class Article < ActiveRecord::Base include Categoryz3::Categorizable end
Usage¶ ↑
Listing categories from an object¶ ↑
You can use the relation ‘categories` to list all categories from a model:
model.categories #=> [category1, category2]
You can also use the ‘categories_list`, this will return the categories ids:
model.categories_list #=> "1, 2"
Adding categories to an object¶ ↑
There are 2 ways for adding categories to an object:
model.categories << category model.categories_list = "1, 2, 3"
Removing categories from an object¶ ↑
To remove a category from the model, you can use the ‘remove_category` method:
model.remove_category category model.remove_categories category1, category2
Category Path¶ ↑
Lists all the categories in the path, from the root one, to the category:
category.path #=> [root_category, some_subcategory, another_subcategory, category]
Categorizable Scopes¶ ↑
inside_category¶ ↑
Lists all objects that belongs to the category or any subcategory of it
Article.inside_category(category)
having_category¶ ↑
Lists all objects that belongs to the category. (No subcategory objects).
Article.having_category(category)
License¶ ↑
MIT License. Copyright 2012 Tiago Scolari.