Class: BeautifulCancancanGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
BeautifulScaffoldCommonMethods
Defined in:
lib/generators/beautiful_cancancan_generator.rb

Instance Method Summary collapse

Instance Method Details

#install_cancancanObject

argument :model, :type => :string, :desc => “Name of model (ex: user)”



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
# File 'lib/generators/beautiful_cancancan_generator.rb', line 10

def install_cancancan
  model = "user"

  gem("cancancan", "3.2.1")

  Bundler.with_unbundled_env do
    run "bundle install"
  end

  # Because generators doesn't work !
  copy_file("app/models/ability.rb")

  # Why that doesn't work... boring...
  #puts rails_command("generate cancan:ability", capture: true)
  # Why that doesn't work too... boring...
  #generate("cancan:ability")

  # current_user method need for CanCan
  current_user_method = ""
  if model != "user" then
    current_user_method = "
def current_user
  current_#{model}
end"
  end

  # Exception for AccessDenied
  inject_into_file("app/controllers/application_controller.rb", "
rescue_from CanCan::AccessDenied do |exception|
  respond_to do |format|
    format.json { head :forbidden, content_type: 'text/html' }
    format.html { redirect_to root_url, :alert => exception.message }
    format.js   { head :forbidden, content_type: 'text/html' }
  end
end
#{current_user_method}
", :after => "class ApplicationController < ActionController::Base\n")

  # Access controlled by CanCanCan (in beautiful_scaffold)
  inject_into_file("app/controllers/application_controller.rb", "#", :before => "before_action :authenticate_#{model}!, :except => [:dashboard]")
end