Sha256: be6eb56f74f81825563f45889c32ed1fd688556c3505db20c6163fc4a3f506ce

Contents?: true

Size: 1.72 KB

Versions: 11

Compression:

Stored size: 1.72 KB

Contents

require "datagrid/columns"

module Datagrid
  class OrderUnsupported < StandardError
  end
  module Ordering

    def self.included(base)
      base.extend         ClassMethods
      base.class_eval do
        include Datagrid::Columns

        datagrid_attribute :order do |value|
          unless value.blank?
            value = value.to_sym
            column = column_by_name(value)
            unless column 
              order_unsupported(value, "no column #{value} in #{self.class}")
            end
            unless column.order
              order_unsupported(
                name, "#{self.class}##{name} don't support order" 
              ) 
            end
            value
          else
            nil
          end

        end

        datagrid_attribute :descending do |value|
          Datagrid::Utils.booleanize(value)
        end
        alias descending? descending

      end
      base.send :include, InstanceMethods
    end # self.included

    module ClassMethods

      def order_unsupported(name, reason)
        raise Datagrid::OrderUnsupported, "Can not sort #{self.inspect} by ##{name}: #{reason}"
      end

    end # ClassMethods

    module InstanceMethods

      def assets
        result = super
        if self.order
          column = column_by_name(self.order)
          result = apply_order(result, column)
        end
        result
      end

      private

      def apply_order(assets, column)

        order = column.order
        if self.descending?
          if column.order_desc
            driver.asc(assets, column.order_desc) 
          else
            driver.desc(assets, order)
          end
        else
          driver.asc(assets, order) 
        end
      end

    end # InstanceMethods

  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
datagrid-0.6.4 lib/datagrid/ordering.rb
datagrid-0.6.3 lib/datagrid/ordering.rb
datagrid-0.6.2 lib/datagrid/ordering.rb
datagrid-0.6.0 lib/datagrid/ordering.rb
datagrid-0.5.4 lib/datagrid/ordering.rb
datagrid-0.5.3 lib/datagrid/ordering.rb
datagrid-0.5.2 lib/datagrid/ordering.rb
datagrid-0.5.1 lib/datagrid/ordering.rb
datagrid-0.5.0 lib/datagrid/ordering.rb
datagrid-0.4.1 lib/datagrid/ordering.rb
datagrid-0.4.0 lib/datagrid/ordering.rb