Module: Listalicious::ActiveRecordExtensions

Defined in:
lib/listalicious.rb

Overview

:nodoc:

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”.



138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/listalicious.rb', line 138

def attach_orderable_scopes
  self.named_scope :ordered_from, lambda { |params|
    return unless 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

    fields.empty? ?
      nil :
      {:order => fields.map{ |field, dir| "#{field} #{dir.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.



114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/listalicious.rb', line 114

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}
  
  attach_orderable_scopes
end