Class: Authorization::InstallGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
Rails::Generators::Migration
Defined in:
lib/generators/authorization/install/install_generator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.next_migration_number(dirname) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/generators/authorization/install/install_generator.rb', line 14

def self.next_migration_number(dirname)
  if ActiveRecord::Base.timestamped_migrations
    Time.now.utc.strftime("%Y%m%d%H%M%S")
  else
    "%.3d" % (current_migration_number(dirname) + 1)
  end
end

Instance Method Details

#install_decl_authObject



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
72
73
74
75
# File 'lib/generators/authorization/install/install_generator.rb', line 22

def install_decl_auth
  habtm_table_name  = "#{name.pluralize}" <= "Roles" ? "#{name.pluralize}Roles" : "Roles#{name.pluralize}" unless options[:user_belongs_to_role]
  habtm_file_glob  = "#{name.pluralize}" <= "Roles" ? 'db/migrate/*create_*_roles*' : 'db/migrate/*create_roles_*' unless options[:user_belongs_to_role]

  generate 'model', "#{name} #{attributes.join(' ')}" if options[:create_user]
  generate 'model', 'Role title:string'

  if options[:user_belongs_to_role]
    inject_into_file "app/models/#{name.singularize.downcase}.rb", "  belongs_to :role\n", after: "ActiveRecord::Base\n"
    generate 'migration', "AddRoleIdTo#{name.camelcase} role_id:integer"
  else
    generate 'migration', "Create#{habtm_table_name} #{name.downcase}:integer role:integer"
    gsub_file Dir.glob(habtm_file_glob).last, 'integer', 'references'
    inject_into_file Dir.glob(habtm_file_glob).last, ", id: false", before: ' do |t|'
    inject_into_file "app/models/role.rb", "  has_and_belongs_to_many :#{name.downcase.pluralize}\n", after: "ActiveRecord::Base\n"
    inject_into_file "app/models/#{name.singularize.downcase}.rb", "  has_and_belongs_to_many :roles\n", after: "ActiveRecord::Base\n"
  end

  rake 'db:migrate' if options[:commit]

  if options[:user_belongs_to_role]
    inject_into_file "app/models/#{name.singularize.downcase}.rb", before: "\nend" do <<-'RUBY'


  def role_symbols
[role.title.to_sym]
  end
    RUBY
    end
  else
    inject_into_file "app/models/#{name.singularize.downcase}.rb", before: "\nend" do <<-'RUBY'


  def role_symbols
(roles || []).map {|r| r.title.to_sym}
  end
    RUBY
    end
  end

  inject_into_file 'db/seeds.rb', after: ".first)\n" do <<-'RUBY'

roles = Role.create([
  {title: 'admin'},
  {title: 'user'}
]) if Role.count == 0
RUBY
  end

  rake 'db:seed' if options[:commit]

  generate 'authorization:rules'
  puts "Please run `rake db:migrate` and `rake db:seed` to finish installing." unless options[:commit]
end