module ActiveRecordExtended::QueryMethods::Either

Constants

XOR_FIELD_KEYS
XOR_FIELD_SQL

Public Instance Methods

either_join(initial_association, fallback_association) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 11
def either_join(initial_association, fallback_association)
  associations        = [initial_association, fallback_association]
  association_options = xor_field_options_for_associations(associations)
  condition__query    = xor_field_sql(association_options) + "= #{table_name}.#{primary_key}"
  outer_joins(associations).where(Arel.sql(condition__query))
end
Also aliased as: either_joins
either_joins(initial_association, fallback_association)
Alias for: either_join
either_order(direction, **associations_and_columns) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 19
def either_order(direction, **associations_and_columns)
  reflected_columns = map_columns_to_tables(associations_and_columns)
  conditional_query = xor_field_sql(reflected_columns) + sort_order_sql(direction)
  outer_joins(associations_and_columns.keys).order(Arel.sql(conditional_query))
end
Also aliased as: either_orders
either_orders(direction, **associations_and_columns)
Alias for: either_order

Private Instance Methods

map_columns_to_tables(associations_and_columns) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 41
def map_columns_to_tables(associations_and_columns)
  if associations_and_columns.respond_to?(:transform_keys)
    associations_and_columns.transform_keys { |assc| reflect_on_association(assc).table_name }
  else
    associations_and_columns.each_with_object({}) do |(assc, value), key_table|
      reflect_table            = reflect_on_association(assc).table_name
      key_table[reflect_table] = value
    end
  end
end
sort_order_sql(dir) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 32
def sort_order_sql(dir)
  ["asc", "desc"].include?(dir.to_s) ? dir.to_s : "asc"
end
xor_field_options(options) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 36
def xor_field_options(options)
  str_args = options.flatten.take(XOR_FIELD_KEYS.size).map(&:to_s)
  Hash[XOR_FIELD_KEYS.zip(str_args)]
end
xor_field_options_for_associations(associations) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 52
def xor_field_options_for_associations(associations)
  associations.each_with_object({}) do |association_name, options|
    reflection = reflect_on_association(association_name)
    options[reflection.table_name] = reflection.foreign_key
  end
end
xor_field_sql(options) click to toggle source
# File lib/active_record_extended/query_methods/either.rb, line 28
def xor_field_sql(options)
  XOR_FIELD_SQL % Hash[xor_field_options(options)]
end