Skip to content

Instantly share code, notes, and snippets.

@willbuilds
Last active August 29, 2015 14:14
Show Gist options
  • Save willbuilds/e0ded4a1c7dfc6d08685 to your computer and use it in GitHub Desktop.
Save willbuilds/e0ded4a1c7dfc6d08685 to your computer and use it in GitHub Desktop.
Chain methods together in an Array (or string, split('.') ) and perform sequentially.Can be used to fetch related object's attributes without explicit ruby code (ie Front-End JS).NOTE: Will fallback to 'nil' instead of throwing error
## Controller
## value = send_chain(@activity, 'asset.product.code')
def try_chain(record, attrib)
attrib.split('.').inject(record) {|o, a| o = o.try(a); o }
end
## Model
## value = send_chain('asset.product.code')
def get_column_value(attrib)
attrib.split('.').inject(self) {|o, a| o = o.try(a); o }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment