Sha256: 0f28fb54a6fa5d189de3b6e98d7e2f88b2267f8b50a5a72fbff35407496dd140

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

module OrderFu
  class AttributeOrder
    attr_accessor :attribute_name, :order_direction

    def initialize(attribute_name, order_direction)
      @attribute_name, @order_direction = attribute_name, order_direction
    end

    def to_s
      "#{@attribute_name} #{@order_direction.to_s.upcase}"
    end

    def <=>(other)
      [self.order_direction.to_s, self.attribute_name.to_s] <=> [other.order_direction.to_s, other.attribute_name.to_s]
    end

    def ==(other)
      (self <=> other) == 0
    end

    def eql?(other)
      self.hash == other.hash
    end

    def hash
      ["AttributeOrder", self.order_direction.to_s, self.attribute_name.to_s].hash
    end
  end

  # ActiveRecord Extention
  module ActiveRecordExtentions
    def add_order_with_order_fu!(sql, order, scope = :auto)
      order = build_order(order)

      scope = scope(:find) if :auto == scope
      scoped_order = build_order(scope[:order]) if scope

      if order
        sql << " ORDER BY #{order}"
        sql << ", #{scoped_order}" if scoped_order
      else
        sql << " ORDER BY #{scoped_order}" if scoped_order
      end
    end

    def build_order(order)
      case order
      when AttributeOrder then order.to_s
      when Array          then order.map { |o| o.to_s } * ','
      else order
      end
    end
  end

  module SymbolExtensions
    [ :asc, :desc ].each do |order_direction|
      define_method(order_direction) do
        AttributeOrder.new(self, order_direction)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sprsquish-order_fu-0.1.0 lib/order_fu.rb
sprsquish-order_fu-0.1.2 lib/order_fu.rb