README.md in calculated_attributes-0.1.3 vs README.md in calculated_attributes-0.1.4

- old
+ new

@@ -1,6 +1,7 @@ -[![Gem Version](https://badge.fury.io/rb/calculated_attributes.svg)](https://badge.fury.io/rb/calculated_attributes) +[![Gem Version](https://badge.fury.io/rb/calculated_attributes.svg)](https://badge.fury.io/rb/calculated_attributes) +[![CircleCI](https://circleci.com/gh/aha-app/calculated_attributes.svg?style=shield)](https://circleci.com/gh/aha-app/calculated_attributes) # CalculatedAttributes Automatically add calculated attributes from accessory select queries to ActiveRecord models. @@ -20,26 +21,28 @@ $ gem install calculated_attributes ## Usage -Add each calculated attribute to your model using the `calculated` keyword. It accepts two parameters: a symbol representing the name of the calculated attribute, and a lambda containing a string to calculate the attribute. +Add each calculated attribute to your model using the `calculated` keyword. It accepts two parameters: a symbol representing the name of the calculated attribute, and a lambda containing a string to calculate the attribute. The lambda can accept arguments. For example, if we have two models, `Post` and `Comment`, and `Comment` has a `post_id` attribute, we might write the following code to add a comments count to each `Post` record in a relation: ```ruby class Post < ActiveRecord::Base ... calculated :comments_count, -> { "select count(*) from comments where comments.post_id = posts.id" } + calculated :comments_count_by_user, ->(user) { ["select count(*) from comments where comments.post_id = posts.id and posts.user_id = '%s'", user.id] } ... end ``` Then, the comments count may be accessed as follows: ```ruby Post.scoped.calculated(:comments_count).first.comments_count +Post.scoped.calculated(comments_count_by_user: user).first.comments_count_by_user #=> 5 ``` Multiple calculated attributes may be attached to each model. If we add a `Tag` model that also has a `post_id`, we can update the Post model as following: @@ -67,17 +70,22 @@ You may also use the `calculated` method on a single model instance, like so: ```ruby Post.first.calculated(:comments_count).comments_count #=> 5 + +Post.first.calculated(comments_count_by_user: user).comments_count_by_user +#=> 0 ``` If you have defined a `calculated` method, results of that method will be returned rather than throwing a method missing error even if you don't explicitly use the `calculated()` call on the instance: ```ruby Post.first.comments_count #=> 5 +Post.first.comments_count_by_user(user) +#=> 0 ``` If you like, you may define `calculated` lambdas using Arel syntax: ```ruby @@ -106,6 +114,6 @@ 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ## Credits -Written by Zach Schneider based on ideas from Chris Waters. \ No newline at end of file +Written by Zach Schneider based on ideas from Chris Waters.