padrino-admin 0.18.1 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. checksums.yaml +4 -4
  2. data/lib/padrino-admin/generators/actions.rb +1 -0
  3. data/lib/padrino-admin/generators/admin_app.rb +36 -17
  4. data/lib/padrino-admin/generators/admin_page.rb +2 -1
  5. data/lib/padrino-admin/generators/keep_files.rb +56 -0
  6. data/lib/padrino-admin/generators/orm.rb +16 -2
  7. data/lib/padrino-admin/generators/templates/assets/stylesheets/application.css +0 -3
  8. data/lib/padrino-admin/generators/templates/erb/app/layouts/application.erb.tt +0 -5
  9. data/lib/padrino-admin/generators/templates/erb/app/layouts/error.erb.tt +0 -5
  10. data/lib/padrino-admin/generators/templates/erb/app/sessions/new.erb.tt +0 -4
  11. data/lib/padrino-admin/generators/templates/erb/page/index.erb.tt +2 -2
  12. data/lib/padrino-admin/generators/templates/haml/app/layouts/application.haml.tt +0 -5
  13. data/lib/padrino-admin/generators/templates/haml/app/layouts/error.haml.tt +0 -5
  14. data/lib/padrino-admin/generators/templates/haml/app/sessions/new.haml.tt +0 -4
  15. data/lib/padrino-admin/generators/templates/haml/page/index.haml.tt +2 -2
  16. data/lib/padrino-admin/generators/templates/page/controller.rb.tt +0 -3
  17. data/lib/padrino-admin/generators/templates/slim/app/layouts/application.slim.tt +0 -5
  18. data/lib/padrino-admin/generators/templates/slim/app/layouts/error.slim.tt +0 -5
  19. data/lib/padrino-admin/generators/templates/slim/app/sessions/new.slim.tt +0 -4
  20. data/lib/padrino-admin/generators/templates/slim/page/index.slim.tt +2 -2
  21. data/lib/padrino-admin/helpers/authentication_helpers.rb +3 -1
  22. data/lib/padrino-admin.rb +21 -1
  23. data/padrino-admin.gemspec +8 -3
  24. data/test/generators/test_admin_app_generator.rb +54 -0
  25. data/test/generators/test_admin_page_generator.rb +126 -0
  26. data/test/generators/test_admin_rerun_generator.rb +244 -0
  27. data/test/test_admin_application.rb +73 -0
  28. metadata +15 -9
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 281388666c8cb872b46f3ce068940e8718006d27375c7a81b5281e09e8a250de
4
- data.tar.gz: e3b4d990cc8c9d48954531eeb3234efadc0d46ab2a63fdf34cce3f1e8ce218ac
3
+ metadata.gz: d4201a847361929f410a70a3254c1a71b1af1f16e599e8c289fd19352424ef6b
4
+ data.tar.gz: dd2c63edb9c513fc90122af641619ce19502de997c2a1d870f08e7ae7256d516
5
5
  SHA512:
6
- metadata.gz: 7c2b5c039a5c8716aaeb1f4e6a1aad7bf61aeee5994cb567e425a3580050d282e473e033037a603ceb85feeef1a84fcb8d0f3d056e5916d97bd2bcec54398e79
7
- data.tar.gz: e58b0d302e3d6ff10a2ae6866e55640819512d6309e06a595138a91ee61e3ff1789abd898dfe233245d97a49dcf366d6014d5d5b8f5ba9d1723c6aa0ebbebb97
6
+ metadata.gz: 10f18575e2a4d40c57c4ce49923be8b84964fa83fbf55e9ba5884d88d7641e0aa72d5a82ef5dcc884b3ead6e069551afaebb120e72f09b50a605426fe1c9cafb
7
+ data.tar.gz: 1ce89c2fd6e3721ece45a02b950063928df23f97655458d37dccb5d1c9bd89d2cbac4257930fcfd02ddea73c65db69de06a6757af4001b19d88aad75d3c7d060
@@ -69,6 +69,7 @@ module Padrino
69
69
  #
70
70
  # @api public
71
71
  def fetch_app_name(app = 'app')
72
+ check_app_existence(app)
72
73
  app_path = destination_root(app, 'app.rb')
73
74
  @app_name ||= File.read(app_path).scan(/module\s(.*?)\n/).flatten[0]
74
75
  end
@@ -16,6 +16,7 @@ module Padrino
16
16
  include Thor::Actions
17
17
  include Padrino::Generators::Actions
18
18
  include Padrino::Generators::Admin::Actions
19
+ include Padrino::Generators::Admin::KeepFiles
19
20
 
20
21
  # Look for custom template files in a generators folder under the project root.
21
22
  def source_paths
@@ -57,26 +58,35 @@ module Padrino
57
58
  @admin_name = options[:admin_name].classify
58
59
  @admin_path = options[:admin_name].underscore
59
60
 
61
+ # Setup Admin Model
62
+ @model_name = options[:admin_model].classify
63
+ @model_singular = @model_name.underscore
64
+ @model_plural = @model_singular.pluralize
65
+ model_path = destination_root('models', "#{@model_singular}.rb")
66
+
67
+ # A plain app (g app admin) or a missing one: an admin app has access control once generated.
68
+ first_install = !line_in_file?(destination_root(@admin_path, 'app.rb'), /Padrino::Admin::AccessControl/)
69
+
70
+ stop_for_model_without_login(model_path) if first_install && !options[:destroy]
71
+
60
72
  store_component_choice(:admin_renderer, tmp_ext)
61
73
 
62
74
  self.behavior = :revoke if options[:destroy]
63
75
 
64
76
  empty_directory destination_root(@admin_path)
65
77
 
66
- # Setup Admin Model
67
- @model_name = options[:admin_model].classify
68
- @model_singular = @model_name.underscore
69
- @model_plural = @model_singular.pluralize
70
-
71
78
  directory 'templates/app', destination_root(@admin_path)
72
79
  directory 'templates/assets', destination_root('public', @admin_path)
73
80
  template 'templates/app.rb.tt', destination_root("#{@admin_path}/app.rb")
74
- inject_into_file destination_root('config/apps.rb'), <<~RUBY.prepend("\n"), before: %r{^Padrino.mount.*\.to\('/'\)$}
75
- Padrino.mount('#{@app_name}::#{@admin_name}', app_file: Padrino.root('#{@admin_path}/app.rb')).to('/#{@admin_path}')
76
- RUBY
81
+ mounted = /^\s*Padrino\.mount\W+#{@app_name}::#{@admin_name}\b/
82
+ if options[:destroy] || !line_in_file?(destination_root('config/apps.rb'), mounted)
83
+ inject_into_file destination_root('config/apps.rb'), <<~RUBY.prepend("\n"), before: %r{^Padrino.mount.*\.to\('/'\)$}
84
+ Padrino.mount('#{@app_name}::#{@admin_name}', app_file: Padrino.root('#{@admin_path}/app.rb')).to('/#{@admin_path}')
85
+ RUBY
86
+ end
77
87
 
78
- unless options[:destroy]
79
- insert_middleware 'ConnectionPoolManagement', @admin_path if orm == :activerecord
88
+ unless options[:destroy] || orm != :activerecord || line_in_file?(destination_root(@admin_path, 'app.rb'), /^\s*use[\s(]+ConnectionPoolManagement\b/)
89
+ insert_middleware 'ConnectionPoolManagement', @admin_path
80
90
  end
81
91
 
82
92
  params = [
@@ -87,7 +97,7 @@ module Padrino
87
97
  params << '-d' if options[:destroy]
88
98
 
89
99
  # An existing model is reused: the model generator would refuse it and exit 1.
90
- model_exists = already_exists?(@model_name, fetch_component_choice(:namespace))
100
+ model_exists = already_exists?(@model_name, fetch_component_choice(:namespace)) || File.exist?(model_path)
91
101
  Padrino::Generators::Model.start(params) if options[:destroy] || !model_exists
92
102
  column = Struct.new(:name, :type)
93
103
  columns = %i[id name surname email].map { |col| column.new(col) }
@@ -100,6 +110,9 @@ module Padrino
100
110
  { name: :role, field_type: :text_field }
101
111
  ]
102
112
 
113
+ controller = destination_root("#{@admin_path}/controllers/#{@model_plural}.rb")
114
+ controller_before = File.binread(controller) if File.exist?(controller)
115
+
103
116
  unless options[:destroy]
104
117
  admin_app = Padrino::Generators::AdminPage.new([@model_singular], root: options[:root], destroy: options[:destroy], admin_model: @model_singular, admin_name: options[:admin_name])
105
118
  admin_app.default_orm = Padrino::Admin::Generators::Orm.new(@model_singular, orm, columns, column_fields)
@@ -107,10 +120,14 @@ module Padrino
107
120
  end
108
121
 
109
122
  # TODO: See this, there's something wrong it's not being applied properly or something because test_account_model_generator last test fails.
110
- template "templates/account/#{orm}.rb.tt", destination_root('models', "#{@model_singular}.rb"), force: true
123
+ template "templates/account/#{orm}.rb.tt", model_path, force: !model_exists
111
124
 
125
+ # Seeds of the admin model stay in place; moving others aside never replaces an earlier move.
112
126
  seed_destination = destination_root('db', 'seeds.rb')
113
- run "mv #{seed_destination} #{destination_root('db/seeds.old')}" if File.exist?(seed_destination)
127
+ seed_backup = destination_root('db/seeds.old')
128
+ if first_install && File.exist?(seed_destination) && !File.exist?(seed_backup) && !line_in_file?(seed_destination, /\b#{@model_name}\b/)
129
+ run "mv #{seed_destination} #{seed_backup}"
130
+ end
114
131
  template 'templates/account/seeds.rb.tt', seed_destination
115
132
 
116
133
  empty_directory destination_root("#{@admin_path}/controllers")
@@ -129,19 +146,21 @@ module Padrino
129
146
  template "templates/#{ext}/app/errors/404.#{ext}.tt", destination_root("#{@admin_path}/views/errors/404.#{ext}")
130
147
  template "templates/#{ext}/app/errors/500.#{ext}.tt", destination_root("#{@admin_path}/views/errors/500.#{ext}")
131
148
 
149
+ gemfile = destination_root('Gemfile')
132
150
  unless options[:destroy]
133
- add_project_module @model_plural
134
- require_dependencies('bcrypt')
151
+ add_missing_project_module @model_plural
152
+ require_dependencies('bcrypt') unless line_in_file?(gemfile, /^\s*gem[\s(]+['"]bcrypt['"]/)
135
153
  end
136
154
 
137
- require_dependencies 'activesupport', version: '>= 3.1'
155
+ require_dependencies 'activesupport', version: '>= 3.1' if options[:destroy] || !line_in_file?(gemfile, /^\s*gem[\s(]+['"]activesupport['"]/)
138
156
 
139
157
  # A nicer select box.
140
158
  # TODO FIXME This doesn't make much sense in here. Review.
141
159
  # gsub_file destination_root("admin/views/#{@model_plural}/_form.#{ext}"), "f.text_field :role, class: :text_field", "f.select :role, options: access_control.roles"
142
160
 
143
161
  # Destroy account only if not logged in.
144
- gsub_file destination_root("#{@admin_path}/controllers/#{@model_plural}.rb"), "if #{@model_singular}.destroy", "if #{@model_singular} != current_account && #{@model_singular}.destroy"
162
+ controller_after = File.binread(controller) if File.exist?(controller)
163
+ gsub_file controller, "if #{@model_singular}.destroy", "if #{@model_singular} != current_account && #{@model_singular}.destroy" if controller_after != controller_before
145
164
  return if self.behavior == :revoke
146
165
 
147
166
  instructions = []
@@ -18,6 +18,7 @@ module Padrino
18
18
  include Thor::Actions
19
19
  include Padrino::Generators::Actions
20
20
  include Padrino::Generators::Admin::Actions
21
+ include Padrino::Generators::Admin::KeepFiles
21
22
 
22
23
  # Look for custom template files in a generators folder under the project root.
23
24
  def source_paths
@@ -66,7 +67,7 @@ module Padrino
66
67
  template "templates/#{ext}/page/index.#{ext}.tt", destination_root("#{@admin_path}/views/#{@orm.name_plural}/index.#{ext}")
67
68
  template "templates/#{ext}/page/new.#{ext}.tt", destination_root("#{@admin_path}/views/#{@orm.name_plural}/new.#{ext}")
68
69
 
69
- options[:destroy] ? remove_project_module(@orm.name_plural) : add_project_module(@orm.name_plural)
70
+ options[:destroy] ? remove_project_module(@orm.name_plural) : add_missing_project_module(@orm.name_plural)
70
71
  end
71
72
  else
72
73
  exit_outside_app_root!
@@ -0,0 +1,56 @@
1
+ module Padrino
2
+ module Generators
3
+ module Admin
4
+ ##
5
+ # Keeps an existing file when its overwrite prompt is left unanswered.
6
+ #
7
+ module KeepFiles
8
+ ##
9
+ # Answers no at the end of input (no terminal, empty pipe), which Thor takes as a yes.
10
+ # Other answers, including piped ones, work as usual.
11
+ #
12
+ module Shell
13
+ def file_collision(destination)
14
+ @resolving_file_collision = true
15
+ super
16
+ ensure
17
+ @resolving_file_collision = false
18
+ end
19
+
20
+ def ask(statement, *args)
21
+ answer = super
22
+ answer.nil? && @resolving_file_collision ? 'n' : answer
23
+ end
24
+ end
25
+
26
+ def shell
27
+ super.extend(Shell)
28
+ end
29
+
30
+ ##
31
+ # Tells whether the file exists and has a line matching the pattern.
32
+ #
33
+ def line_in_file?(path, pattern)
34
+ File.exist?(path) && File.binread(path).match?(pattern)
35
+ end
36
+
37
+ ##
38
+ # Adds the access_control permission unless the app has one for the controller, edited or not.
39
+ #
40
+ def add_missing_project_module(controller)
41
+ add_project_module(controller) unless line_in_file?(destination_root("#{@admin_path}/app.rb"), /^\s*role\.project_module[\s(]+:#{controller}\b/)
42
+ end
43
+
44
+ ##
45
+ # Stops when the admin can't log in with an existing model and nobody is left to answer whether to replace it.
46
+ #
47
+ def stop_for_model_without_login(path)
48
+ return if !File.exist?(path) || line_in_file?(path, /\bauthenticate\b/) || $stdin.tty? || !$stdin.eof?
49
+
50
+ raise Thor::Error, "#{path} has no authenticate method and no input is left to confirm replacing it. " \
51
+ 'Add the method to the model, or run the generator in a terminal to choose whether to replace the file.'
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -22,7 +22,7 @@ module Padrino
22
22
  def initialize(name, orm, columns = nil, column_fields = nil)
23
23
  name = name.to_s
24
24
  @klass_name = name.underscore.camelize
25
- @klass = @klass_name.constantize rescue nil
25
+ @klass = load_klass
26
26
  @name_param = name.underscore.gsub('/', '_')
27
27
  @name_singular = name.underscore.gsub(%r{^.*/}, '') # convert submodules i.e. FooBar::Jank.all # => jank
28
28
  @name_plural = @name_singular.pluralize
@@ -35,6 +35,7 @@ module Padrino
35
35
  # needed when reading the model's columns to generate a page, so destroying a page skips it.
36
36
  def check_model_orm
37
37
  return unless @columns.nil?
38
+ raise OrmError, "Model '#{klass_name}' could not be loaded#{' because the project failed to load' if @boot_failed}!\n#{@load_error.class}: #{@load_error.message}" if @load_error
38
39
  raise OrmError, "Model '#{klass_name}' could not be found!\nPerhaps you would like to run 'bundle exec padrino g model #{klass_name}' to create it first?" if @klass.nil?
39
40
 
40
41
  base = MODEL_BASES[orm]
@@ -49,7 +50,7 @@ module Padrino
49
50
 
50
51
  def field_type(type)
51
52
  type = :string if type.nil?
52
- type = type.to_s.demodulize.downcase.to_sym unless type.is_a?(Symbol)
53
+ type = Padrino::Inflections.demodulize(type).downcase.to_sym unless type.is_a?(Symbol)
53
54
 
54
55
  case type
55
56
  when :integer, :float, :decimal then :text_field
@@ -140,6 +141,19 @@ module Padrino
140
141
  else "@#{name_singular}.errors.include?(:#{field})"
141
142
  end
142
143
  end
144
+
145
+ private
146
+
147
+ # Returns nil when the model is not defined. A model that failed to load keeps its error in
148
+ # @load_error, whether looking it up raised it or loading the project (config/boot.rb) did.
149
+ def load_klass
150
+ @klass_name.constantize
151
+ rescue StandardError => e
152
+ missing = Padrino::Admin.missing_constant?(e, @klass_name)
153
+ @load_error = missing ? Padrino::Generators.boot_error : e
154
+ @boot_failed = missing && !@load_error.nil?
155
+ nil
156
+ end
143
157
  end
144
158
  end
145
159
  end
@@ -139,7 +139,6 @@ footer p {
139
139
 
140
140
  /* -- Begin Errors -- */
141
141
  .custom-error {
142
- font-family: 'Varela', sans-serif;
143
142
  font-size: 1.5em;
144
143
  width: 500px;
145
144
  margin: 100px auto 0;
@@ -218,7 +217,6 @@ footer p {
218
217
  margin-top: 10px;
219
218
  height: 20px; /* Bootstrap 3.4 makes it 50px, which pushes the navbar down */
220
219
  padding: 0px 15px;
221
- font-family: 'Varela', sans-serif;
222
220
  text-transform: uppercase;
223
221
  font-size: 2.5em;
224
222
  line-height: 1em;
@@ -318,7 +316,6 @@ footer p {
318
316
  /* --- End Application::List --- */
319
317
  /* --- Begin Application::Base --- */
320
318
  .base-text {
321
- font-family: 'Varela', sans-serif;
322
319
  width: 730px;
323
320
  margin: 40px auto 0;
324
321
  font-size: 1.45em;
@@ -1,15 +1,10 @@
1
1
  <!DOCTYPE html>
2
2
  <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
3
3
  <head>
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
9
5
  <meta name=viewport content='width=device-width,initial-scale=1' />
10
6
  <title><%%= @title.present? ? "#{@title} | Padrino Admin" : "Padrino Admin" %></title>
11
7
  <%%= favicon_tag "favicon.ico" %>
12
- <link href='http://fonts.googleapis.com/css?family=Varela' rel=stylesheet />
13
8
  <%%= stylesheet_link_tag 'bootstrap', 'application' %>
14
9
  </head>
15
10
 
@@ -1,15 +1,10 @@
1
1
  <!DOCTYPE html>
2
2
  <html lang="en">
3
3
  <head>
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
9
5
  <meta name=viewport content='width=device-width,initial-scale=1' />
10
6
  <title><%%= @title.present? ? "#{@title} | Padrino Admin" : "#{pat(:custom_errors.title)} | Padrino Admin" %></title>
11
7
  <%%= favicon_tag "favicon.ico" %>
12
- <link href='http://fonts.googleapis.com/css?family=Varela' rel=stylesheet />
13
8
  <%%= stylesheet_link_tag 'bootstrap', 'application' %>
14
9
  </head>
15
10
 
@@ -1,10 +1,6 @@
1
1
  <!DOCTYPE html>
2
2
  <html lang="en">
3
3
  <head>
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
9
5
  <meta name=viewport content='width=device-width,initial-scale=1' />
10
6
  <title><%%= @title.present? ? "#{@title} | Padrino Admin" : "#{pat('login.title')} | Padrino Admin" %></title>
@@ -52,8 +52,8 @@
52
52
  <%- @orm.columns.each_with_index do |column, i| -%>
53
53
  <%- if column.name == "created_at" || column.name == "updated_at" -%>
54
54
  <td class=list-column> <%%= time_ago_in_words <%= @orm.name_singular %>.<%= column.name %> %></td>
55
- <%- elsif column.type == :boolean -%>
56
- <td class=list-column> <%%= <%= @orm.name_singular %>.<%= column.name %> ? tag_icon(:ok) : tag_icon(:remove) %> </td>
55
+ <%- elsif @orm.field_type(column.type) == :check_box -%>
56
+ <td class=list-column> <%%= tag_icon(<%= @orm.name_singular %>.<%= column.name %> ? :check : :times) + content_tag(:span, <%= @orm.name_singular %>.<%= column.name %>.to_s, class: 'sr-only') unless <%= @orm.name_singular %>.<%= column.name %>.nil? %> </td>
57
57
  <%- else -%>
58
58
  <td class=list-column> <%%= <%= @orm.name_singular %>.<%= column.name %> %> </td>
59
59
  <%- end -%>
@@ -1,15 +1,10 @@
1
1
  !!! 5
2
2
  %html{lang: 'en'}
3
3
  %head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  %meta{content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type'}
9
5
  %meta{name: :viewport, content: 'width=device-width,initial-scale=1'}
10
6
  %title= @title.present? ? "#{@title} | Padrino Admin" : 'Padrino Admin'
11
7
  =favicon_tag 'favicon.ico'
12
- %link{href: 'http://fonts.googleapis.com/css?family=Varela', rel: :stylesheet}
13
8
  =stylesheet_link_tag 'bootstrap', 'application'
14
9
 
15
10
  %body
@@ -1,15 +1,10 @@
1
1
  !!! 5
2
2
  %html{lang: 'en'}
3
3
  %head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  %meta{content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type'}
9
5
  %meta{name: :viewport, content: 'width=device-width,initial-scale=1'}
10
6
  %title= @title.present? ? "#{@title} | Padrino Admin" : "#{pat(:custom_errors.title)} | Padrino Admin"
11
7
  =favicon_tag 'favicon.ico'
12
- %link{href: 'http://fonts.googleapis.com/css?family=Varela', rel: :stylesheet}
13
8
  =stylesheet_link_tag 'bootstrap', 'application'
14
9
 
15
10
  %body
@@ -1,10 +1,6 @@
1
1
  !!! 5
2
2
  %html{lang: 'en'}
3
3
  %head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  %meta{content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type'}
9
5
  %meta{name: :viewport, content: 'width=device-width,initial-scale=1'}
10
6
  %title= @title.present? ? "#{@title} | Padrino Admin" : "#{pat('login.title')} | Padrino Admin"
@@ -39,8 +39,8 @@
39
39
  <%- @orm.columns.each_with_index do |column, i| -%>
40
40
  <%- if column.name == "created_at" || column.name == "updated_at" -%>
41
41
  %td.list-column=time_ago_in_words <%= @orm.name_singular %>.<%= column.name %>
42
- <%- elsif column.type == :boolean -%>
43
- %td.list-column= <%= @orm.name_singular %>.<%= column.name %> ? tag_icon(:ok) : tag_icon(:remove)
42
+ <%- elsif @orm.field_type(column.type) == :check_box -%>
43
+ %td.list-column= tag_icon(<%= @orm.name_singular %>.<%= column.name %> ? :check : :times) + content_tag(:span, <%= @orm.name_singular %>.<%= column.name %>.to_s, class: 'sr-only') unless <%= @orm.name_singular %>.<%= column.name %>.nil?
44
44
  <%- else -%>
45
45
  %td.list-column=<%= @orm.name_singular %>.<%= column.name %>
46
46
  <%- end -%>
@@ -30,7 +30,6 @@
30
30
  if @<%= @orm.name_singular %>
31
31
  render '<%= @orm.name_plural %>/edit'
32
32
  else
33
- flash[:warning] = pat(:create_error, model: '<%= @orm.name_singular %>', id: params[:id])
34
33
  halt 404
35
34
  end
36
35
  end
@@ -49,7 +48,6 @@
49
48
  render '<%= @orm.name_plural %>/edit'
50
49
  end
51
50
  else
52
- flash[:warning] = pat(:update_warning, model: '<%= @orm.name_singular %>', id: params[:id])
53
51
  halt 404
54
52
  end
55
53
  end
@@ -65,7 +63,6 @@
65
63
  end
66
64
  redirect url(:<%= @orm.name_plural %>, :index)
67
65
  else
68
- flash[:warning] = pat(:delete_warning, model: '<%= @orm.name_singular %>', id: params[:id])
69
66
  halt 404
70
67
  end
71
68
  end
@@ -1,15 +1,10 @@
1
1
  doctype 5
2
2
  html lang='en'
3
3
  head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  meta content='text/html; charset=utf-8' http-equiv='Content-Type'
9
5
  meta name='viewport' content='width=device-width,initial-scale=1'
10
6
  title = @title.present? ? "#{@title} | Padrino Admin" : "Padrino Admin"
11
7
  = favicon_tag 'favicon.ico'
12
- link href='http://fonts.googleapis.com/css?family=Varela' rel='stylesheet'
13
8
  = stylesheet_link_tag 'bootstrap', 'application'
14
9
 
15
10
  body
@@ -1,15 +1,10 @@
1
1
  doctype 5
2
2
  html lang="en" xmlns="http://www.w3.org/1999/xhtml"
3
3
  head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  meta content='text/html; charset=utf-8' http-equiv='Content-Type'
9
5
  meta name='viewport' content='width=device-width,initial-scale=1'
10
6
  title = @title.present? ? "#{@title} | Padrino Admin" : "#{pat(:custom_errors.title)} | Padrino Admin"
11
7
  = favicon_tag 'favicon.ico'
12
- link href='http://fonts.googleapis.com/css?family=Varela' rel='stylesheet'
13
8
  = stylesheet_link_tag 'bootstrap', 'application'
14
9
 
15
10
  body
@@ -1,10 +1,6 @@
1
1
  doctype 5
2
2
  html lang="en" xmlns="http://www.w3.org/1999/xhtml"
3
3
  head
4
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
5
- <!--[if lt IE 9]>
6
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
7
- <![endif]-->
8
4
  meta content='text/html; charset=utf-8' http-equiv='Content-Type'
9
5
  meta name='viewport' content='width=device-width,initial-scale=1'
10
6
  title = @title.present? ? "#{@title} | Padrino Admin" : "#{pat('login.title')} | Padrino Admin"
@@ -37,8 +37,8 @@ div class="tabs-content"
37
37
  <%- @orm.columns.each_with_index do |column, i| -%>
38
38
  <%- if column.name == 'created_at' || column.name == 'updated_at' -%>
39
39
  td class='list-column' = time_ago_in_words <%= @orm.name_singular %>.<%= column.name %>
40
- <%- elsif column.type == :boolean -%>
41
- td class='list-column' = <%= @orm.name_singular %>.<%= column.name %> ? tag_icon(:ok) : tag_icon(:remove)
40
+ <%- elsif @orm.field_type(column.type) == :check_box -%>
41
+ td class='list-column' = tag_icon(<%= @orm.name_singular %>.<%= column.name %> ? :check : :times) + content_tag(:span, <%= @orm.name_singular %>.<%= column.name %>.to_s, class: 'sr-only') unless <%= @orm.name_singular %>.<%= column.name %>.nil?
42
42
  <%- else -%>
43
43
  td class='list-column' = <%= @orm.name_singular %>.<%= column.name %>
44
44
  <%- end -%>
@@ -99,7 +99,9 @@ module Padrino
99
99
 
100
100
  def admin_model_obj
101
101
  @_admin_model_obj ||= Padrino::Inflections.constantize(settings.admin_model)
102
- rescue NameError
102
+ rescue NameError => e
103
+ raise unless Padrino::Admin.missing_constant?(e, settings.admin_model)
104
+
103
105
  raise Padrino::Admin::AccessControlError, "You must define an #{settings.admin_model} Model"
104
106
  end
105
107
  end
data/lib/padrino-admin.rb CHANGED
@@ -20,6 +20,26 @@ module Padrino
20
20
  I18n.load_path += Dir["#{__dir__}/padrino-admin/locale/**/*.yml"]
21
21
  end
22
22
  alias included registered
23
+
24
+ ##
25
+ # Whether +error+, raised looking up the constant +name+, says that constant (or one of its
26
+ # namespaces) is not defined, rather than coming from the code that defining it ran. The
27
+ # error must name a segment of +name+ and have been raised on that segment's parent, so a
28
+ # model whose body references another constant with the same short name isn't "missing".
29
+ #
30
+ def missing_constant?(error, name)
31
+ return false unless error.instance_of?(NameError)
32
+
33
+ segments = name.to_s.sub(/\A::/, '').split('::')
34
+ return false unless error.receiver.is_a?(::Module)
35
+
36
+ segments.each_index.any? do |index|
37
+ parent = index.zero? ? 'Object' : segments.first(index).join('::')
38
+ segments[index] == error.name.to_s && error.receiver.name == parent
39
+ end
40
+ rescue ArgumentError
41
+ false
42
+ end
23
43
  end
24
44
  end
25
45
  end
@@ -29,7 +49,7 @@ end
29
49
  #
30
50
  begin
31
51
  require 'padrino-gen'
32
- Padrino::Generators.load_paths << Dir["#{__dir__}/padrino-admin/generators/{actions,orm,admin_app,admin_page}.rb"]
52
+ Padrino::Generators.load_paths << Dir["#{__dir__}/padrino-admin/generators/{actions,keep_files,orm,admin_app,admin_page}.rb"]
33
53
  rescue LoadError
34
54
  # do nothing if padrino-gen is not available
35
55
  end
@@ -8,16 +8,21 @@ Gem::Specification.new do |s|
8
8
  s.authors = ['Padrino Team', 'Nathan Esquenazi', "Davide D'Agostino", 'Arthur Chiu']
9
9
  s.email = 'padrinorb@gmail.com'
10
10
  s.summary = 'Admin Dashboard for Padrino'
11
- s.homepage = 'http://www.padrinorb.com'
11
+ s.homepage = 'https://padrinorb.com'
12
12
  s.description = 'Admin View for Padrino applications'
13
+ s.required_ruby_version = '>= 2.7.8'
13
14
  s.required_rubygems_version = '>= 1.3.6'
14
15
  s.version = Padrino.version
15
- s.date = Time.now.strftime('%Y-%m-%d')
16
16
  s.license = 'MIT'
17
+ s.metadata = {
18
+ 'bug_tracker_uri' => 'https://github.com/padrino/padrino-framework/issues',
19
+ 'changelog_uri' => 'https://github.com/padrino/padrino-framework/blob/master/CHANGES.rdoc',
20
+ 'documentation_uri' => 'https://padrinorb.com/guides/',
21
+ 'source_code_uri' => 'https://github.com/padrino/padrino-framework'
22
+ }
17
23
 
18
24
  s.extra_rdoc_files = Dir['*.rdoc']
19
25
  s.files = `git ls-files`.split("\n")
20
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
21
26
  s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
22
27
  s.require_paths = ['lib']
23
28
  s.rdoc_options = ['--charset=UTF-8']
@@ -16,6 +16,13 @@ describe 'AdminAppGenerator' do
16
16
  Object.send(:remove_const, :Account) if defined?(Account)
17
17
  end
18
18
 
19
+ it 'should stop with a message in a project without an app' do
20
+ capture_io { generate(:project, 'sample_project', '--lean', "--root=#{@apptmp}", '-d', 'sequel', '-e', 'erb') }
21
+ out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "-r=#{@apptmp}/sample_project") }.status }
22
+ assert_match(/Unable to locate 'App' application/, out)
23
+ refute_path_exists "#{@apptmp}/sample_project/admin"
24
+ end
25
+
19
26
  it 'should fail outside app root' do
20
27
  out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "-r=#{@apptmp}") }.status }
21
28
  assert_match(/not at the root/, out)
@@ -261,9 +268,56 @@ describe 'AdminAppGenerator' do
261
268
  assert_equal '200', code, "#{page} includes #{src}, which is not served"
262
269
  end
263
270
  end
271
+
272
+ it "should load only the admin's own assets on the #{engine} admin pages, with no IE conditional comments" do
273
+ skip 'the sqlite3 gem is only bundled on MRI' if RUBY_ENGINE == 'jruby'
274
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{engine}") }
275
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
276
+ script = <<~'RUBY'
277
+ ENV['RACK_ENV'] = 'test'
278
+ %w[sequel haml slim erubi nokogiri rack/test].each { |lib| require lib }
279
+ Sequel.extension :migration
280
+ Sequel.sqlite('db/sample_project_test.db') { |db| Sequel::Migrator.run(db, 'db/migrate') }
281
+ require File.expand_path('config/boot')
282
+ account_id = Account.dataset.insert(email: 'admin@example.com', role: 'admin', crypted_password: 'unused')
283
+
284
+ browser = Rack::Test::Session.new(Padrino.application)
285
+ check = lambda do |page|
286
+ browser.get(page)
287
+ puts "PAGE #{page} #{browser.last_response.status}"
288
+ html = Nokogiri::HTML(browser.last_response.body)
289
+ html.css('link[href], script[src]').each { |tag| puts "ASSET #{page} #{tag['href'] || tag['src']}" }
290
+ html.xpath('//comment()').each { |comment| puts "COMMENT #{page} #{comment.text.split.join(' ')}" }
291
+ end
292
+ check.call('/admin/sessions/new')
293
+ browser.env('rack.session', SampleProject::Admin.session_id => account_id)
294
+ check.call('/admin/')
295
+ check.call('/admin/accounts/edit/0')
296
+ RUBY
297
+ env = { 'BUNDLE_GEMFILE' => File.expand_path('../../../Gemfile', __dir__) }
298
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: "#{@apptmp}/sample_project")
299
+ assert status.success?, err
300
+ statuses = out.lines.grep(/\APAGE /).map { |line| line.split[1, 2] }
301
+ assert_equal [['/admin/sessions/new', '200'], ['/admin/', '200'], ['/admin/accounts/edit/0', '404']], statuses
302
+ assets = out.lines.grep(/\AASSET /).map(&:split)
303
+ refute_empty assets
304
+ assets.each do |(_, page, url)|
305
+ assert_match %r{\A/(?!/)}, url, "#{page} loads #{url} from another site"
306
+ end
307
+ assert_empty out.lines.grep(/\ACOMMENT .*\[if /)
308
+ end
264
309
  end
265
310
  end
266
311
 
312
+ it 'should name in the admin stylesheet only fonts it loads itself' do
313
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=erb') }
314
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
315
+ stylesheet = File.read("#{@apptmp}/sample_project/public/admin/stylesheets/application.css")
316
+ loaded = stylesheet.scan(/@font-face\s*\{\s*font-family:\s*['"]([^'"]+)['"]/).flatten
317
+ named = stylesheet.scan(/font-family:([^;}]+)/).flatten.flat_map { |list| list.split(',') }.map { |font| font.strip.delete(%q('")) }
318
+ assert_empty named.uniq - loaded - %w[serif sans-serif monospace system-ui inherit]
319
+ end
320
+
267
321
  it 'should correctly generate a new padrino admin application with a custom model' do
268
322
  capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=activerecord', '-e=slim') }
269
323
  capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project", '-m=User') }
@@ -1,6 +1,7 @@
1
1
  require_relative '../helper'
2
2
  require_relative '../fixtures/sequel'
3
3
  require 'nokogiri'
4
+ require 'padrino-gen/generators/cli'
4
5
 
5
6
  describe 'AdminPageGenerator' do
6
7
  before do
@@ -13,6 +14,12 @@ describe 'AdminPageGenerator' do
13
14
  end
14
15
 
15
16
  describe 'the admin page generator' do
17
+ it 'should stop with a message in a project without an app' do
18
+ capture_io { generate(:project, 'sample_project', '--lean', "--root=#{@apptmp}", '-d', 'sequel', '-e', 'erb') }
19
+ out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'foo', "-r=#{@apptmp}/sample_project") }.status }
20
+ assert_match(/Unable to locate 'App' application/, out)
21
+ end
22
+
16
23
  it 'should fail outside app root' do
17
24
  out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'foo', "-r=#{@apptmp}/sample_project") }.status }
18
25
  assert_match(/not at the root/, out)
@@ -48,6 +55,17 @@ describe 'AdminPageGenerator' do
48
55
  assert_no_match_in_file(/project_module :foos/, "#{@apptmp}/sample_project/admin/app.rb")
49
56
  end
50
57
 
58
+ it 'should fail without an existent model whose name repeats a namespace' do
59
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
60
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
61
+ Object.const_set(:RepeatedPageShop, Module.new)
62
+ RepeatedPageShop.const_set(:Order, Module.new)
63
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'repeated_page_shop/order/order', "-r=#{@apptmp}/sample_project") }.status }
64
+ assert_match(/Model 'RepeatedPageShop::Order::Order' could not be found/, err)
65
+ ensure
66
+ Object.send(:remove_const, :RepeatedPageShop) if Object.const_defined?(:RepeatedPageShop, false)
67
+ end
68
+
51
69
  %w[erb haml slim].each do |renderer|
52
70
  it "should destroy pages whose models were already removed (#{renderer})" do
53
71
  Object.const_set(:GoneWidget, Class.new(Sequel::Model(:friends)))
@@ -95,6 +113,31 @@ describe 'AdminPageGenerator' do
95
113
  assert_no_dir_exists("#{@apptmp}/sample_project/admin/views/friends")
96
114
  end
97
115
 
116
+ it 'should report a model that fails to load with the project instead of a missing one' do
117
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
118
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
119
+ File.write("#{@apptmp}/sample_project/models/broken_widget.rb", "class BrokenWidget < Sequel::Modle; end\n")
120
+ File.write("#{@apptmp}/sample_project/config/boot.rb", "require_relative '../models/broken_widget'\n")
121
+ capture_io { Padrino::Generators::Cli.new([], root: "#{@apptmp}/sample_project").load_boot }
122
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'broken_widget', "-r=#{@apptmp}/sample_project") }.status }
123
+ assert_match(/Model 'BrokenWidget' could not be loaded because the project failed to load!\nNameError: uninitialized constant Sequel::Modle/, err)
124
+ refute_match(/could not be found/, err)
125
+ assert_no_dir_exists("#{@apptmp}/sample_project/admin/views/broken_widgets")
126
+ ensure
127
+ Padrino::Generators.boot_error = nil
128
+ end
129
+
130
+ it 'should report the error of a model that fails to load when looked up' do
131
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
132
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
133
+ File.write("#{@apptmp}/broken_page_sample.rb", "module BrokenPageSample; class Gadget; MissingConcern; end; end\n")
134
+ Object.autoload(:BrokenPageSample, "#{@apptmp}/broken_page_sample.rb")
135
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'broken_page_sample/gadget', "-r=#{@apptmp}/sample_project") }.status }
136
+ assert_match(/Model 'BrokenPageSample::Gadget' could not be loaded!\nNameError: uninitialized constant BrokenPageSample::Gadget::MissingConcern/, err)
137
+ ensure
138
+ Object.send(:remove_const, :BrokenPageSample) if Object.const_defined?(:BrokenPageSample, false)
139
+ end
140
+
98
141
  it 'should fail when the project has no orm and the model is not activerecord' do
99
142
  capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
100
143
  capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
@@ -197,6 +240,89 @@ describe 'AdminPageGenerator' do
197
240
  assert_equal %w[list-menu-wrapper list-menu-wrapper-disabled], classes.call(page.at_css(link).parent)
198
241
  end
199
242
  end
243
+
244
+ # Mongoid reports a boolean field's type as the class Mongoid::Boolean, not as :boolean.
245
+ [nil, 'Mongoid::Boolean'].each do |type_name|
246
+ it "should show boolean columns in the list as icons the stylesheet draws (#{renderer}#{", #{type_name}" if type_name})" do
247
+ Sequel::Model.db.create_table!(:switches) do
248
+ primary_key :id
249
+ String :name
250
+ TrueClass :enabled
251
+ end
252
+ # JRuby's jdbc-sqlite stores booleans as integers and loads 0 as 0, which is truthy.
253
+ Object.const_set(:Switch, Class.new(Sequel::Model(:switches)) { plugin :typecast_on_load, :enabled })
254
+ Switch.create(name: 'on', enabled: true)
255
+ Switch.create(name: 'off', enabled: false)
256
+ Switch.create(name: 'unset', enabled: nil)
257
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{renderer}") }
258
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
259
+ if type_name
260
+ boolean = Class.new
261
+ boolean.define_singleton_method(:to_s) { type_name }
262
+ columns = Switch.db_schema.map { |name, info| Padrino::Admin::Generators::Orm::Column.new(name, name == :enabled ? boolean : info[:type]) }
263
+ Padrino::Admin::Generators::Orm.any_instance.stubs(:columns).returns(columns)
264
+ end
265
+ capture_io { generate(:admin_page, 'switch', "--root=#{@apptmp}/sample_project") }
266
+ views = "#{@apptmp}/sample_project/admin/views"
267
+ mock_app do
268
+ set :views, views
269
+ helpers Padrino::Admin::Helpers::ViewHelpers
270
+ controllers :switches do
271
+ get(:index) do
272
+ @switches = Switch.order(:id).all
273
+ render 'switches/index', layout: false
274
+ end
275
+ get(:new) {}
276
+ get(:edit, with: :id) {}
277
+ delete(:destroy, with: :id) {}
278
+ delete(:destroy_many) {}
279
+ end
280
+ end
281
+ get '/switches'
282
+ assert_equal 200, last_response.status
283
+ page = Nokogiri::HTML(last_response.body)
284
+ column = page.css('#list thead th').map { |th| th.text.strip }.index('Enabled')
285
+ on, off, unset = page.css('#list tbody tr').map { |row| row.css('td')[column] }
286
+ icons = ->(cell) { cell.css('i.fa').flat_map { |icon| icon['class'].split - ['fa'] } }
287
+ refute_empty icons.call(on)
288
+ refute_empty icons.call(off)
289
+ refute_equal icons.call(on), icons.call(off)
290
+ assert_equal 'true', on.at_css('.sr-only')&.text
291
+ assert_equal 'false', off.at_css('.sr-only')&.text
292
+ assert_empty unset.children.to_s.strip
293
+ stylesheet = File.read("#{@apptmp}/sample_project/public/admin/stylesheets/application.css")
294
+ undrawn = (icons.call(on) + icons.call(off)).reject { |icon| stylesheet.include?(".#{icon}:before") }
295
+ assert_empty undrawn, 'the stylesheet draws no glyph for these icons'
296
+ ensure
297
+ Object.send(:remove_const, :Switch) if Object.const_defined?(:Switch, false)
298
+ Sequel::Model.db.drop_table?(:switches)
299
+ end
300
+ end
301
+ end
302
+
303
+ it 'should not carry a flash over to the next page when a record is not found' do
304
+ saved = Object.send(:remove_const, :SampleProject) if Object.const_defined?(:SampleProject, false)
305
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=erb') }
306
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
307
+ capture_io { generate(:admin_page, 'friend', "--root=#{@apptmp}/sample_project") }
308
+ mock_app do
309
+ enable :sessions
310
+ helpers Padrino::Admin::Helpers::ViewHelpers
311
+ get(:flash) { flash.keys.join(',') }
312
+ end
313
+ Object.const_set(:SampleProject, Module.new).const_set(:Admin, @app)
314
+ load "#{@apptmp}/sample_project/admin/controllers/friends.rb"
315
+ get '/friends/edit/999'
316
+ assert_equal 404, last_response.status
317
+ put '/friends/update/999'
318
+ assert_equal 404, last_response.status
319
+ delete '/friends/destroy/999'
320
+ assert_equal 404, last_response.status
321
+ get '/flash'
322
+ assert_equal '', last_response.body
323
+ ensure
324
+ Object.send(:remove_const, :SampleProject) if Object.const_defined?(:SampleProject, false)
325
+ Object.const_set(:SampleProject, saved) if saved
200
326
  end
201
327
 
202
328
  it 'should correctly generate a new padrino admin application with multiple models at the same time' do
@@ -0,0 +1,244 @@
1
+ require_relative '../helper'
2
+ require_relative '../fixtures/sequel'
3
+
4
+ describe 'AdminRerun' do
5
+ before do
6
+ @apptmp = "#{Dir.tmpdir}/padrino-tests/#{SecureRandom.hex}"
7
+ `mkdir -p #{@apptmp}`
8
+ @project = "#{@apptmp}/sample_project"
9
+ end
10
+
11
+ after do
12
+ `rm -rf #{@apptmp}`
13
+ end
14
+
15
+ # Thor reads each answer through its line editor, which returns nil at the end of input.
16
+ def with_answers(*answers)
17
+ Thor::LineEditor.stubs(:readline).returns(*answers, nil)
18
+ yield
19
+ end
20
+
21
+ def with_stdin(input)
22
+ original = $stdin
23
+ $stdin = StringIO.new(input)
24
+ yield
25
+ ensure
26
+ $stdin = original
27
+ end
28
+
29
+ def edit(file)
30
+ path = "#{@project}/#{file}"
31
+ File.write(path, "#{yield(File.read(path))}\n# edited\n")
32
+ end
33
+
34
+ def snapshot
35
+ Dir.glob("#{@project}/**/*", File::FNM_DOTMATCH).select { |path| File.file?(path) }.to_h { |path| [path, File.read(path)] }
36
+ end
37
+
38
+ %w[activerecord mongoid sequel].each do |orm|
39
+ describe "with #{orm}" do
40
+ before do
41
+ Object.send(:remove_const, :Account) if defined?(Account)
42
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
43
+ capture_io { generate(:admin_app, "--root=#{@project}") }
44
+ %w[models/account.rb db/seeds.rb admin/controllers/accounts.rb admin/views/base/index.haml public/admin/stylesheets/application.css].each do |file|
45
+ edit(file) { |content| content }
46
+ end
47
+ edit('admin/app.rb') { |content| content.sub("'/accounts'", "'/accounts' # staff only") }
48
+ edit('config/apps.rb') { |content| content.sub(".to('/admin')", ".to('/backend')") }
49
+ edit('Gemfile') { |content| content.sub("gem 'bcrypt'", "gem 'bcrypt', '>= 3.1'") }
50
+ end
51
+
52
+ it 'should keep edited files when g admin runs again at the end of input' do
53
+ edited = snapshot
54
+ out, = capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
55
+ assert_equal edited, snapshot
56
+ assert_match(%r{skip\s+admin/app\.rb}, out)
57
+ end
58
+
59
+ it 'should still overwrite a file when the conflict is answered with yes' do
60
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
61
+ assert_no_match_in_file(/# edited/, "#{@project}/models/account.rb")
62
+ assert_no_match_in_file(/# edited/, "#{@project}/admin/controllers/accounts.rb")
63
+ assert_match_in_file(/# edited/, "#{@project}/config/apps.rb")
64
+ end
65
+
66
+ it 'should keep the lines of app.rb when a yes rewrites it' do
67
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
68
+ app = "#{@project}/admin/app.rb"
69
+ assert_no_match_in_file(/# edited/, app)
70
+ assert_match_in_file(%r{role\.project_module :accounts, '/accounts'}, app)
71
+ orm == 'activerecord' ? assert_match_in_file(/use ConnectionPoolManagement/, app) : assert_no_match_in_file(/ConnectionPoolManagement/, app)
72
+ assert_match_in_file(/account != current_account && account\.destroy/, "#{@project}/admin/controllers/accounts.rb")
73
+ end
74
+
75
+ it 'should keep edited seeds that delegate to another file at the end of input' do
76
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
77
+ edited = snapshot
78
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
79
+ assert_equal edited, snapshot
80
+ end
81
+
82
+ it 'should send delegating seeds through the overwrite prompt' do
83
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
84
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
85
+ assert_match_in_file(/Account\.new\(/, "#{@project}/db/seeds.rb")
86
+ assert_no_file_exists("#{@project}/db/seeds.old")
87
+ end
88
+
89
+ it 'should move seeds without the model aside for the first install of another admin app' do
90
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
91
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}", '-a=other') } }
92
+ assert_match_in_file(/staff\.rb/, "#{@project}/db/seeds.old")
93
+ assert_match_in_file(/Account\.new\(/, "#{@project}/db/seeds.rb")
94
+ end
95
+
96
+ it 'should keep gems declared with parentheses' do
97
+ edit('Gemfile') do |content|
98
+ content.sub(/^gem 'bcrypt'.*$/, "gem('bcrypt', '>= 3.1')").sub(/^gem 'activesupport'.*$/, "gem('activesupport', '>= 3.1')")
99
+ end
100
+ edited = snapshot
101
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
102
+ assert_equal edited, snapshot
103
+ assert_equal 1, File.read("#{@project}/Gemfile").scan(/bcrypt/).size
104
+ assert_equal 1, File.read("#{@project}/Gemfile").scan(/activesupport/).size
105
+ end
106
+
107
+ it 'should not stop a re-run for a model that gets authenticate elsewhere' do
108
+ File.write("#{@project}/models/account.rb", "class Account\n extend Credentials\nend\n")
109
+ edited = snapshot
110
+ capture_io do
111
+ with_stdin('') do
112
+ with_answers { generate(:admin_app, "--root=#{@project}") }
113
+ rescue SystemExit => e
114
+ flunk "the admin generator exited with status #{e.status}"
115
+ end
116
+ end
117
+ assert_equal edited, snapshot
118
+ end
119
+
120
+ it 'should leave a removed destroy guard removed at the end of input' do
121
+ edit('admin/controllers/accounts.rb') { |content| content.sub('account != current_account && ', '') }
122
+ edited = snapshot
123
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
124
+ assert_equal edited, snapshot
125
+ end
126
+ end
127
+
128
+ describe "with #{orm} and an account model that can't log in" do
129
+ before do
130
+ Object.send(:remove_const, :Account) if defined?(Account)
131
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
132
+ FileUtils.mkdir_p("#{@project}/models")
133
+ File.write("#{@project}/models/account.rb", "class Account\nend\n")
134
+ end
135
+
136
+ it 'should stop before writing anything at the end of input' do
137
+ before_run = snapshot
138
+ _, err = capture_io do
139
+ with_stdin('') { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "--root=#{@project}") }.status }
140
+ end
141
+ assert_match(/no authenticate method/, err)
142
+ assert_equal before_run, snapshot
143
+ end
144
+
145
+ it 'should replace the model when the prompt is answered with yes' do
146
+ capture_io { with_stdin("y\n") { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } } }
147
+ assert_match_in_file(/def self\.authenticate/, "#{@project}/models/account.rb")
148
+ end
149
+ end
150
+
151
+ describe "with #{orm} and an admin app that only partly exists" do
152
+ before do
153
+ Object.send(:remove_const, :Account) if defined?(Account)
154
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
155
+ end
156
+
157
+ it 'should add the missing lines at the end of input and keep a partial app.rb' do
158
+ FileUtils.mkdir_p("#{@project}/admin")
159
+ File.write("#{@project}/admin/app.rb", "# partial\n")
160
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
161
+ assert_equal "# partial\n", File.read("#{@project}/admin/app.rb")
162
+ assert_match_in_file(%r{Padrino\.mount\('SampleProject::Admin'.*\.to\('/admin'\)}, "#{@project}/config/apps.rb")
163
+ assert_match_in_file(/gem 'bcrypt'/, "#{@project}/Gemfile")
164
+ end
165
+
166
+ it 'should stop for a plain model after g app admin at the end of input' do
167
+ capture_io { generate(:app, 'admin', "-r=#{@project}") }
168
+ FileUtils.mkdir_p("#{@project}/models")
169
+ File.write("#{@project}/models/account.rb", "class Account\nend\n")
170
+ before_run = snapshot
171
+ capture_io do
172
+ with_stdin('') { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "--root=#{@project}") }.status }
173
+ end
174
+ assert_equal before_run, snapshot
175
+ end
176
+
177
+ it 'should add every line after g app admin and a yes' do
178
+ capture_io { generate(:app, 'admin', "-r=#{@project}") }
179
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
180
+ assert_match_in_file(/gem 'bcrypt'/, "#{@project}/Gemfile")
181
+ assert_match_in_file(/gem 'activesupport'/, "#{@project}/Gemfile")
182
+ assert_equal 1, File.read("#{@project}/config/apps.rb").scan(/^Padrino\.mount\('SampleProject::Admin'/).size
183
+ assert_match_in_file(%r{role\.project_module :accounts, '/accounts'}, "#{@project}/admin/app.rb")
184
+ end
185
+ end
186
+ end
187
+
188
+ describe 'the admin page generator' do
189
+ before do
190
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=haml') }
191
+ capture_io { generate(:admin_app, "--root=#{@project}") }
192
+ capture_io { with_answers { generate(:admin_page, 'section', "-r=#{@project}") } }
193
+ end
194
+
195
+ it 'should add the permission of a new page at the end of input' do
196
+ assert_match_in_file(%r{role\.project_module :sections, '/sections'}, "#{@project}/admin/app.rb")
197
+ end
198
+
199
+ it 'should add the permission when the controller came from g controller' do
200
+ capture_io { generate(:controller, 'widgets', '-a=admin', "-r=#{@project}") }
201
+ Object.const_set(:Widget, Class.new(Sequel::Model(:sections)))
202
+ capture_io { with_answers { generate(:admin_page, 'widget', "-r=#{@project}") } }
203
+ assert_match_in_file(%r{role\.project_module :widgets, '/widgets'}, "#{@project}/admin/app.rb")
204
+ ensure
205
+ Object.send(:remove_const, :Widget) if defined?(Widget)
206
+ end
207
+
208
+ it 'should keep edited files when it runs again at the end of input' do
209
+ edit('admin/controllers/sections.rb') { |content| content }
210
+ edit('admin/views/sections/index.haml') { |content| content }
211
+ edit('admin/app.rb') { |content| content.sub("'/sections'", "'/sections' # staff only") }
212
+ edited = snapshot
213
+ capture_io { with_answers { generate(:admin_page, 'section', "-r=#{@project}") } }
214
+ assert_equal edited, snapshot
215
+ end
216
+
217
+ describe 'with a piped answer' do
218
+ before do
219
+ @controller = "#{@project}/admin/controllers/sections.rb"
220
+ File.write(@controller, "# edited\n")
221
+ end
222
+
223
+ def rerun_answering(answer)
224
+ capture_io { with_answers(answer) { generate(:admin_page, 'section', "-r=#{@project}") } }
225
+ end
226
+
227
+ it 'should overwrite the file when the answer is yes' do
228
+ rerun_answering('y')
229
+ assert_no_match_in_file(/# edited/, @controller)
230
+ end
231
+
232
+ it 'should keep the file when the answer is no' do
233
+ rerun_answering('n')
234
+ assert_equal "# edited\n", File.read(@controller)
235
+ end
236
+
237
+ it 'should keep the file when input runs out after asking for the diff' do
238
+ Thor::Shell::Basic.any_instance.stubs(:show_diff)
239
+ rerun_answering('d')
240
+ assert_equal "# edited\n", File.read(@controller)
241
+ end
242
+ end
243
+ end
244
+ end
@@ -402,6 +402,79 @@ describe 'AdminApplication' do
402
402
  assert_raises(Padrino::Admin::AccessControlError) { access_control.roles_for }
403
403
  end
404
404
 
405
+ describe 'admin model' do
406
+ def mock_admin_app(admin_model)
407
+ mock_app do
408
+ register Padrino::Admin::AccessControl
409
+ set :admin_model, admin_model
410
+ get('/current') { current_account.inspect }
411
+ end
412
+ end
413
+
414
+ it 'should say a missing admin model must be defined' do
415
+ mock_admin_app 'MissingAdminSample::Account'
416
+ error = assert_raises(Padrino::Admin::AccessControlError) { get '/current' }
417
+ assert_equal 'You must define an MissingAdminSample::Account Model', error.message
418
+ end
419
+
420
+ it 'should say a missing admin model must be defined when its name repeats a namespace' do
421
+ Object.const_set(:RepeatedAdminSample, Module.new)
422
+ mock_admin_app 'RepeatedAdminSample::RepeatedAdminSample'
423
+ error = assert_raises(Padrino::Admin::AccessControlError) { get '/current' }
424
+ assert_equal 'You must define an RepeatedAdminSample::RepeatedAdminSample Model', error.message
425
+ ensure
426
+ Object.send(:remove_const, :RepeatedAdminSample) if Object.const_defined?(:RepeatedAdminSample, false)
427
+ end
428
+
429
+ it 'should raise the error of a top-level admin model whose body names another constant like it' do
430
+ Dir.mktmpdir do |dir|
431
+ File.write("#{dir}/colliding_top_account.rb", <<~RUBY)
432
+ module CollidingTopMixins; end
433
+ class CollidingTopAccount
434
+ include CollidingTopMixins::CollidingTopAccount
435
+ end
436
+ RUBY
437
+ Object.autoload(:CollidingTopAccount, "#{dir}/colliding_top_account.rb")
438
+ mock_admin_app 'CollidingTopAccount'
439
+ error = assert_raises(NameError) { get '/current' }
440
+ assert_match(/CollidingTopMixins::CollidingTopAccount/, error.message)
441
+ end
442
+ ensure
443
+ %i[CollidingTopAccount CollidingTopMixins].each { |name| Object.send(:remove_const, name) if Object.const_defined?(name, false) }
444
+ end
445
+
446
+ it 'should raise the error of an admin model whose body names another constant like it' do
447
+ Dir.mktmpdir do |dir|
448
+ File.write("#{dir}/colliding_admin_sample.rb", <<~RUBY)
449
+ module CollidingAdminSample
450
+ module Mixins; end
451
+ class Account
452
+ include Mixins::Account
453
+ end
454
+ end
455
+ RUBY
456
+ Object.autoload(:CollidingAdminSample, "#{dir}/colliding_admin_sample.rb")
457
+ mock_admin_app 'CollidingAdminSample::Account'
458
+ error = assert_raises(NameError) { get '/current' }
459
+ assert_match(/Mixins::Account/, error.message)
460
+ end
461
+ ensure
462
+ Object.send(:remove_const, :CollidingAdminSample) if Object.const_defined?(:CollidingAdminSample, false)
463
+ end
464
+
465
+ it 'should raise the error of an admin model that fails to load' do
466
+ Dir.mktmpdir do |dir|
467
+ File.write("#{dir}/broken_admin_sample.rb", "module BrokenAdminSample; class Account; MissingConcern; end; end\n")
468
+ Object.autoload(:BrokenAdminSample, "#{dir}/broken_admin_sample.rb")
469
+ mock_admin_app 'BrokenAdminSample::Account'
470
+ error = assert_raises(NameError) { get '/current' }
471
+ assert_match(/MissingConcern/, error.message)
472
+ end
473
+ ensure
474
+ Object.send(:remove_const, :BrokenAdminSample) if Object.const_defined?(:BrokenAdminSample, false)
475
+ end
476
+ end
477
+
405
478
  it 'should humanize project module names without ActiveSupport' do
406
479
  assert_equal 'Blog posts', Padrino::Admin::AccessControl::ProjectModule.new(:blog_posts, '/blog_posts').human_name
407
480
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: padrino-admin
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.18.1
4
+ version: 0.18.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Padrino Team
@@ -11,7 +11,7 @@ authors:
11
11
  autorequire:
12
12
  bindir: bin
13
13
  cert_chain: []
14
- date: 2026-10-31 00:00:00.000000000 Z
14
+ date: 2026-11-01 00:00:00.000000000 Z
15
15
  dependencies:
16
16
  - !ruby/object:Gem::Dependency
17
17
  name: padrino-core
@@ -19,28 +19,28 @@ dependencies:
19
19
  requirements:
20
20
  - - '='
21
21
  - !ruby/object:Gem::Version
22
- version: 0.18.1
22
+ version: 0.18.2
23
23
  type: :runtime
24
24
  prerelease: false
25
25
  version_requirements: !ruby/object:Gem::Requirement
26
26
  requirements:
27
27
  - - '='
28
28
  - !ruby/object:Gem::Version
29
- version: 0.18.1
29
+ version: 0.18.2
30
30
  - !ruby/object:Gem::Dependency
31
31
  name: padrino-helpers
32
32
  requirement: !ruby/object:Gem::Requirement
33
33
  requirements:
34
34
  - - '='
35
35
  - !ruby/object:Gem::Version
36
- version: 0.18.1
36
+ version: 0.18.2
37
37
  type: :runtime
38
38
  prerelease: false
39
39
  version_requirements: !ruby/object:Gem::Requirement
40
40
  requirements:
41
41
  - - '='
42
42
  - !ruby/object:Gem::Version
43
- version: 0.18.1
43
+ version: 0.18.2
44
44
  description: Admin View for Padrino applications
45
45
  email: padrinorb@gmail.com
46
46
  executables: []
@@ -59,6 +59,7 @@ files:
59
59
  - lib/padrino-admin/generators/actions.rb
60
60
  - lib/padrino-admin/generators/admin_app.rb
61
61
  - lib/padrino-admin/generators/admin_page.rb
62
+ - lib/padrino-admin/generators/keep_files.rb
62
63
  - lib/padrino-admin/generators/orm.rb
63
64
  - lib/padrino-admin/generators/templates/account/activerecord.rb.tt
64
65
  - lib/padrino-admin/generators/templates/account/mongoid.rb.tt
@@ -159,13 +160,18 @@ files:
159
160
  - test/generators/test_account_model_generator.rb
160
161
  - test/generators/test_admin_app_generator.rb
161
162
  - test/generators/test_admin_page_generator.rb
163
+ - test/generators/test_admin_rerun_generator.rb
162
164
  - test/helper.rb
163
165
  - test/test_admin_application.rb
164
166
  - test/test_locale.rb
165
- homepage: http://www.padrinorb.com
167
+ homepage: https://padrinorb.com
166
168
  licenses:
167
169
  - MIT
168
- metadata: {}
170
+ metadata:
171
+ bug_tracker_uri: https://github.com/padrino/padrino-framework/issues
172
+ changelog_uri: https://github.com/padrino/padrino-framework/blob/master/CHANGES.rdoc
173
+ documentation_uri: https://padrinorb.com/guides/
174
+ source_code_uri: https://github.com/padrino/padrino-framework
169
175
  post_install_message:
170
176
  rdoc_options:
171
177
  - "--charset=UTF-8"
@@ -175,7 +181,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
175
181
  requirements:
176
182
  - - ">="
177
183
  - !ruby/object:Gem::Version
178
- version: '0'
184
+ version: 2.7.8
179
185
  required_rubygems_version: !ruby/object:Gem::Requirement
180
186
  requirements:
181
187
  - - ">="