ismasan (owner)

Revisions

gist: 199612 Download_button fork
public
Public Clone URL: git://gist.github.com/199612.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Put this in an initializer (config/initializers/common_scopes.rb) or library file.
#
module CommonScopes
 
  module ClassMethods
    # Sort given fields ASC or DESC
    #
    # Example:
    #
    # class Post < ActiveRecord::Base
    # extend CommonAr::ClassMethods
    #
    # sortable_with :title => 'The title', :created_at => 'Created on'
    # end
    #
    # Now you can sort with:
    # 'title_asc'
    # 'title_desc'
    # 'created_at_asc'
    # 'created_at_desc'
    #
    # @posts = Post.sort_with(params[:sort]).paginate(:page => params[:page])
    #
    # Post.sortable_fields #=> {:title_asc => 'The title', :created_at => 'Created on'}
    #
    def sortable_with(fields = {})
      sorts = fields.inject({}) do |h,f|
        h[:"#{f.first}_asc"] = "#{f.last} a-z"
        h[:"#{f.first}_desc"] = "#{f.last} z-a"
        h
      end
      write_inheritable_attribute(:sortable_fields,sorts)
      class_inheritable_reader :sortable_fields
      named_scope :sort_with, lambda { |*args|
        return {} if args.compact.blank?
        k = args.first.to_sym
        return {} if !sortable_fields.has_key?(k)
        {:order => k.to_s.sub('_desc',' desc').sub('_asc',' asc')} # who has time to learn proper RegEx
      }
    end
 
    # Search given fields with SQL LIKE
    #
    # Example:
    #
    # class Post < ActiveRecord::Base
    # extend CommonAr::ClassMethods
    #
    # likeable_with :title, :body
    # end
    #
    # Now your LIKE queries will look in title and body
    # You can combine scopes.
    #
    # @posts = Post.sort_with(params[:sort]).like(params[:q]).paginate(:page => params[:page])
    #
    def likeable_with(*fields)
      # TODO: validate that schema has these fields
      named_scope :like, lambda {|q|
        return {} if q.blank? || !q.respond_to?(:to_s)
        t = ActiveRecord::Base.connection.quote("%#{q}%")
        conditions = fields.collect{|f| "#{f} LIKE #{t}" }.join(' OR ')
        {:conditions => conditions}
      }
    end
 
  end
 
 
end