Module: Methods

Defined in:
lib/crud_for/methods.rb

Instance Method Summary collapse

Instance Method Details

#crud_for(model, options = {}) ⇒ Object



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
# File 'lib/crud_for/methods.rb', line 3

def crud_for(model, options={})
  
  _options = {
    :create => true,
    :update => true,
    :destroy => true,
    :search => defined?(MetaSearch),
    :paginate => defined?(WillPaginate)
  }
  
  _options.merge!(options)
  
  expose(model.to_sym)

  if _options[:paginate] && _options[:search]
    expose(model.to_s.pluralize.to_sym) { search.paginate(:page => params[:page]) }
  else
    if _options[:paginate]
      expose(model.to_s.pluralize.to_sym) { model.to_s.camelize.constantize.paginate(:page => params[:page]) }
    else
      if _options[:search]
        expose(model.to_s.pluralize.to_sym) { search.all }
      else
        expose(model.to_s.pluralize.to_sym) { model.to_s.camelize.constantize.all }
      end
    end
  end
  
  expose(:search) { model.to_s.camelize.constantize.search(params[:search]) } if _options[:search]
    
  self.class_eval %"
    def create
      if #{model}.save
        redirect_to #{model.to_s.pluralize}_url, :notice => I18n.t(:create_success, :model => #{model.to_s.camelize.constantize}.human_name)
      else
        render 'new'
      end
    end
  " if _options[:create]
  
  self.class_eval %"
    def update
      if #{model}.update_attributes(params['#{model.to_sym}'])
        redirect_to #{model.to_s.pluralize}_url, :notice => I18n.t(:update_success, :model => #{model.to_s.camelize.constantize}.human_name)
      else
        render 'edit'
      end
    end
  " if _options[:update]
  
  self.class_eval %"
    def destroy
      #{model}.destroy
      redirect_to #{model.to_s.pluralize}_url, :notice => I18n.t(:destroy_success, :model => #{model.to_s.camelize.constantize}.human_name)
    end
  " if _options[:destroy]
  
end