Created
September 27, 2013 14:23
-
-
Save basgys/6729375 to your computer and use it in GitHub Desktop.
This module allows to create a virtual field from multiple fields
This file contains 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
# = AggregateField | |
# | |
# This module allows to create a virtual field from multiple fields | |
# | |
# Example: | |
# | |
# class DummyClass | |
# include AggregateField | |
# | |
# attr_accessor :first_name, :last_name | |
# aggregate_field :full_name, composed_of: [:first_name, :last_name], separated_by: ' ' | |
# end | |
# | |
# Author : Bastien Gysler <[email protected]> | |
module AggregateField | |
extend ActiveSupport::Concern | |
DEFAULT_SEPARATOR = ' '.freeze | |
module ClassMethods | |
# Create a virtual field from different fields | |
# | |
# Parameters: | |
# - field_name (virtual field name) | |
# - composed_of (list of fields aggregated) | |
# - separated_by (separator) [optionnal] | |
def aggregate_field(field_name, options = {}) | |
options[:composed_of] and options[:composed_of].kind_of?(Array) or raise ArgumentError, "\"composed_of\" option must be given (Array)!" | |
options[:separated_by] ||= DEFAULT_SEPARATOR | |
define_method(field_name) do | |
options[:composed_of].map{|field| public_send(field)}.compact.join(options[:separated_by]) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment