Skip to content

Instantly share code, notes, and snippets.

@basgys
Created September 27, 2013 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save basgys/6729375 to your computer and use it in GitHub Desktop.
Save basgys/6729375 to your computer and use it in GitHub Desktop.
This module allows to create a virtual field from multiple fields
# = 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 <basgys@gmail.com>
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