Listable collections
Makes collections accessible from a string list in rails.
Install
Put this line in your Gemfile:
gem 'listable_collections'
Then bundle:
$ bundle
Usage
Associations
If you want to list a has_many association:
class Shop < ActiveRecord::Base
has_many :products
list :products, attribute: :name
end
Associated records won't be touched but changes will be tracked using the following helpers:
shop.products.map(&:name) => ['iPhone']
shop.product_list => 'iPhone'
shop.product_list = 'iPod,iMac'
shop.products.map(&:name) => ['iPhone']
shop.added_products_to_list => ['iMac']
shop.removed_products_from_list => ['iPod']
NOTE: Because detecting wich record has been removed by an attribute will fire multiple queries, is recommended do this check before save all at once and not dynamically.
Attributes
If you want to list an array attribute:
class Product < ActiveRecord::Base
serialize :sizes, Array
list :sizes
end
The attribute will be synced and chances will be tracked using the following helpers:
product.sizes => ['64GB']
product.size_list => '64GB'
product.size_list = '32GB,128GB'
product.sizes => ['32GB','128GB']
product.added_sizes_to_list => ['128GB']
product.removed_sizes_from_list => ['64GB']
In some cases you may need to run some logic after changes, you can use callbacks for it:
class Shop < ActiveRecord::Base
has_many :product
list :products, attribute: :name, after_add: :product_added, after_remove: :product_removed
def product_added(name)
# Some logic
end
def product_removed(name)
# Some logic
end
end
Contributing
Because we've limited resources we'll mainly add features and keep a compatibility range close to what we need in our projects. However, contributions are more than welcome if someone wants to make any improvement.
Credits
This gem is maintained and funded by mmontossi.
License
It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.