Module: Listalicious::ActiveRecordExtensions

Defined in:
lib/listalicious.rb

Defined Under Namespace

Classes: OrderableConfiguration

Instance Method Summary collapse

Instance Method Details

#attach_orderable_scopesObject

Attaches the ordered_from named scope to the model requesting it. The named scope can be chained in the controller by using:

Users.ordered_from(params).paginate :page => params, :per_page => 2

The params are expected to be in a specific style:

eg. order[]=last_name:desc&order[]=first_name:asc

Which will generate the order clause “last_name DESC, first_name ASC”.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/listalicious.rb', line 145

def attach_orderable_scopes
  self.named_scope :ordered_from, lambda { |params|
    fields = []
    if params.include?(:order) and params[:order][self.table_name.to_sym]
      fields = params[:order][self.table_name.to_sym].collect do |field_and_dir|
        field, dir = field_and_dir.split(':')
        self.orderable_fields.include?(field) ? [field, dir.to_s.downcase] : nil
      end.compact
    end

    if self.default_order && fields.empty? || self.default_order[:options][:stable]
      fields << [self.default_order[:field], self.default_order[:direction]]
    end
    
    fields.empty? ?
      nil :
      {:order => fields.map{ |field, dir| "#{field} #{dir.to_s.downcase == 'desc' ? 'DESC' : 'ASC'}" }.join(', ')}
  }
end

#orderable_fields(&config_block) ⇒ Object

Makes a given model orderable for lists

To specify that a model behaves according to the Listalicious order style call orderable_fields. The orderable_fields method takes a configuration block.

Example

orderable_fields do

only :first_name, :last_name
default :last_name

end

Configuration Methods

only

Provide fields that are orderable.

except

Provide fields that are not orderable, with the default list being all fields.

default

Provide the default sort field, optionally a direction, and additional options.

Notes:

  • If only or except are not called within the block, all fields on the model will be orderable, this includes things like id, and password/password salt columns.

  • If default isn’t called, the first field will be considered the default, asc being the default direction.



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/listalicious.rb', line 77

def orderable_fields(&config_block)
  cattr_accessor :orderable_fields, :default_order

  # make all columns orderable, incase only or except aren't called in the configuration block
  self.orderable_fields = column_names.map { |column_name| column_name.to_s }

  OrderableConfiguration.new(self).instance_eval(&config_block)
  self.orderable_fields.collect!{ |field| field.to_s }

  self.default_order ||= {:field => self.orderable_fields.first, :direction => :desc, :options => {}}

  attach_orderable_scopes
end