Module: ComparableByAttr
- Includes:
- Comparable
- Defined in:
- lib/comparable_by_attr.rb
Overview
Allow simple definitions for object comparisons
Class Method Summary collapse
-
.included(klass) ⇒ Object
rubocop:disable Metrics/MethodLength class_eval wrapper.
Class Method Details
.included(klass) ⇒ Object
rubocop:disable Metrics/MethodLength class_eval wrapper
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/comparable_by_attr.rb', line 6 def self.included(klass) klass.class_eval do @__attr_precedence = nil # attr_compare allows selection of specific instance variables and order # to use within the comparison of objects created off the class # # Example: # class IgnoreC # include ComparableByAttr # attr_compare :a, :b # # def initialize(a, b, c) # @a = a # @b = b # @c = c # end # end # # Arguments: # *prec = (Optional Precedence Map) def self.attr_compare(*prec) attr_prec = prec.map do |attr| "@#{attr}".to_sym end @__attr_precedence = attr_prec end def <=>(other) prec = self.class.instance_variable_get(:@__attr_precedence) comp_order = prec || instance_variables.sort this = comp_order.map { |field| instance_variable_get(field) } that = comp_order.map { |field| other.instance_variable_get(field) } this <=> that end end end |