Created
November 20, 2015 08:21
-
-
Save dmitriy-kiriyenko/05a917e0ac4067fedffe to your computer and use it in GitHub Desktop.
Grabs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Use this to denormalize a field in activerecord | |
| # or to cache an attribute. | |
| # | |
| # Usage: | |
| # | |
| # class User < ActiveRecord::Base | |
| # belongs_to :company | |
| # end | |
| # | |
| # class Project < ActiveRecord::Base | |
| # extend Grabs | |
| # belongs_to :user | |
| # | |
| # grabs :company_id, from: :user | |
| # # This line is essentially equivalent to | |
| # before_validation do | |
| # self.company_id = user.company_id | |
| # end | |
| # end | |
| # | |
| # What you can do: | |
| # | |
| # grabs :company_id, from: :user | |
| # grabs :name, from: user, as: :author_name | |
| # grabs :something, from: :somewhere, on: :create | |
| # | |
| module Grabs | |
| def grabs(field, options = {}) | |
| from = options.delete(:from) { raise "You must provide ':from' option" } | |
| target = options.delete(:as) { field } | |
| before_validation options do | |
| source = self.public_send(from) | |
| self.public_send("#{target}=", source.public_send(field)) if source | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment