Module: Raymond::Model::ClassMethods

Defined in:
lib/raymond/model.rb

Overview

the methods in this module will become class methods

Instance Method Summary collapse

Instance Method Details

#allow_sort_by(*params) ⇒ Object

Define all columns or attributes, that may be sorted upon, by this method

Parameters:

  • params (Array, Hash)

    can be an array of column names a single parameter with a Hash of options

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/raymond/model.rb', line 17

def allow_sort_by(*params)
  @sort_attributes ||= []

  # give the use a little bit more freedom by allowing to pass an array of column names
  params = params.first if params.size == 1 && params.first.kind_of?(Array)

  options = params.pop if params.last.kind_of?(Hash)

  raise ArgumentError.new('Method allow_sort_by takes either an array of column names or' +
      'a single column name with a optional hash of options.') if params.size != 1 && options

  params = params.map(&:to_sym)

  params = [{params.first => options}] if options

  # the items of params must all be column names, if params are symbols

  @sort_attributes += params
end

#secondary_sort_attr(attr, direction = :up) ⇒ Object

Raises:

  • (ArgumentError)


55
56
57
58
59
60
# File 'lib/raymond/model.rb', line 55

def secondary_sort_attr(attr, direction = :up)
  raise ArgumentError.new("First argument of secondary_sort_attr must be a column name.") unless self.column_names.include?(attr.to_s)
  raise ArgumentError.new("Second argument of secondary_sort_attr must be one of #{SORTING_DIRECTIONS.keys.map{|key| ":#{key}"}}.") unless SORTING_DIRECTIONS.keys.include?(direction)
  @secondary_sort_attr = attr
  @secondary_sort_direction = direction
end

#sort_attributesObject



37
38
39
40
# File 'lib/raymond/model.rb', line 37

def sort_attributes
  raise "Trying to sort with no sort attributes defined." unless @sort_attributes
  @sort_attributes.map{|attr| attr.kind_of?(Symbol) ? attr : attr.keys.first}
end

#sort_proc(attr) ⇒ Object

, direction)



42
43
44
45
46
47
# File 'lib/raymond/model.rb', line 42

def sort_proc(attr)#, direction)
  hash = @sort_attributes.detect{|obj| obj.kind_of?(Hash) && obj[attr]}
  method_result = hash && hash[attr] && hash[attr][:method]
  return method_result if method_result
  hash && hash[attr] && hash[attr][:db] == false && Proc.new{|obj| obj.send(attr)}
end

#sql_sort_order(attr, direction) ⇒ Object



49
50
51
52
53
# File 'lib/raymond/model.rb', line 49

def sql_sort_order(attr, direction)
  second = @secondary_sort_attr ? "#{@secondary_sort_attr} #{SORTING_DIRECTIONS[@secondary_sort_direction]}" : nil
  first = (@sort_attributes || []).include?(attr) ? "#{attr} #{SORTING_DIRECTIONS[direction]}" : nil
  [first, second].compact.join(', ')
end