padrino-admin 0.18.6 → 0.18.7

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c7b12e8d41a5d8fdbe9b15b56547ae2825ed4182ba30596c46f25babedc18db7
4
- data.tar.gz: 5a1d7f69f994c2bf6523abc43071812e01078b53c38882a90b27778cc0729f3d
3
+ metadata.gz: dc6b03553b3da10dcaf9cb18c9b4d8d128808724118b81a45fb87d78c2fc971c
4
+ data.tar.gz: 743d189e0d60fd2954f213309fe3985f3d08ef1fab7f19bb6c2b33a11aa53a05
5
5
  SHA512:
6
- metadata.gz: b3152108af502bbe4c871e1db552c781d0a8034239ee9ee0ad06c157babc4fbac21c1e0c8d9710fa0988c159da3965cdadecf8727af3ee7650d7bc6ab0540f34
7
- data.tar.gz: bf7aa8c02877470733d1198f8489687a3a4a7b43e147d3b55e1f9e0a9e7f21eb4f994ac9785ee628e7b43d27a4a711c603907046fe3f387d6dfbc11406ea5f57
6
+ metadata.gz: 11f8c6dd039e56c375576b280d09bb6bd8fd07ceda75454526d39b4b8a87679e280dc36ddc6eebbfb5ca615e218033e65b18a73bbdc7d068a1c6c2e0b907fbcc
7
+ data.tar.gz: 9ea156e96571e01cb6d6c42c850984520cc08f8b4cf2264d2ecc54985b14e6ed1cc64a2e97598cd41536df7ad3ee6161ec2b5a602eb8933d54a0818c59729959
@@ -17,6 +17,9 @@ module Padrino
17
17
  sequel: 'Sequel::Model'
18
18
  }.freeze
19
19
 
20
+ # Column types of numbers with a fractional part.
21
+ FRACTIONAL_TYPES = %i[float decimal bigdecimal].freeze
22
+
20
23
  attr_reader :klass_name, :klass, :name_plural, :name_singular, :orm, :name_param
21
24
 
22
25
  def initialize(name, orm, columns = nil, column_fields = nil)
@@ -49,11 +52,12 @@ module Padrino
49
52
  end
50
53
 
51
54
  def field_type(type)
52
- type = :string if type.nil?
53
- type = Padrino::Inflections.demodulize(type).downcase.to_sym unless type.is_a?(Symbol)
54
-
55
- case type
56
- when :integer, :float, :decimal then :text_field
55
+ case type_name(type)
56
+ when :integer, *FRACTIONAL_TYPES then :number_field
57
+ when :date then :date_field
58
+ # Mongoid's times keep their offset only in a text field: a datetime-local input drops it.
59
+ when :datetime, :timestamptz then orm == :mongoid ? :text_field : :datetime_local_field
60
+ when :time then orm == :mongoid ? :text_field : :time_field
57
61
  when :string then :text_field
58
62
  when :text then :text_area
59
63
  when :boolean then :check_box
@@ -78,7 +82,11 @@ module Padrino
78
82
  column_fields = columns.dup
79
83
  column_fields.reject! { |column| excluded_columns.include?(column.name.to_s) }
80
84
  @column_fields ||= column_fields.map do |column|
81
- { name: column.name, field_type: field_type(column.type) }
85
+ # An enum reads back as its name, which a number input can't hold.
86
+ input = enum?(column.name) ? :text_field : field_type(column.type)
87
+ # A number input takes only whole numbers unless its step allows fractions.
88
+ step = 'any' if input == :number_field && FRACTIONAL_TYPES.include?(type_name(column.type))
89
+ { name: column.name, field_type: input, step: step }
82
90
  end
83
91
  end
84
92
 
@@ -86,9 +94,12 @@ module Padrino
86
94
  "#{klass_name}.all"
87
95
  end
88
96
 
97
+ # Must return nil for a missing id: Active Record's find raises, and so does Mongoid's
98
+ # unless raise_not_found_error is off.
89
99
  def find(params = nil)
90
100
  case orm
91
- when :activerecord, :mongoid then "#{klass_name}.find(#{params})"
101
+ when :activerecord then "#{klass_name}.find_by(#{klass_name}.primary_key => #{params})"
102
+ when :mongoid then "#{klass_name}.where(_id: #{params}).first"
92
103
  when :sequel then "#{klass_name}[#{params}]"
93
104
  else raise OrmError, "Adapter #{orm} is not yet supported!"
94
105
  end
@@ -122,8 +133,8 @@ module Padrino
122
133
  def find_by_ids(params = nil)
123
134
  case orm
124
135
  when :sequel then "#{klass_name}.where(id: #{params})"
125
- when :mongoid then "#{klass_name}.find(#{params})"
126
- else find(params)
136
+ when :activerecord, :mongoid then "#{klass_name}.find(#{params})"
137
+ else raise OrmError, "Adapter #{orm} is not yet supported!"
127
138
  end
128
139
  end
129
140
 
@@ -144,6 +155,32 @@ module Padrino
144
155
 
145
156
  private
146
157
 
158
+ # Whether the model maps the column's values to names: an Active Record enum, or a Sequel
159
+ # enum plugin column whose reader returns the name.
160
+ # ceiling: Sequel's plugin keeps no public list of its columns, so this reads the module it
161
+ # defines the readers in; if that changes, enum columns get number inputs again.
162
+ def enum?(column_name)
163
+ return false unless @klass
164
+
165
+ case orm
166
+ when :activerecord
167
+ @klass.respond_to?(:defined_enums) && @klass.defined_enums.key?(column_name.to_s)
168
+ when :sequel
169
+ @klass.ancestors.any? do |ancestor|
170
+ readers = ancestor.instance_variable_get(:@enum_methods) if ancestor.is_a?(Class)
171
+ readers&.method_defined?(column_name)
172
+ end
173
+ else false
174
+ end
175
+ end
176
+
177
+ # A column's type as a lowercase symbol: Active Record and Sequel give a symbol, Mongoid a
178
+ # class (BigDecimal => :bigdecimal, Mongoid::Boolean => :boolean).
179
+ def type_name(type)
180
+ return :string if type.nil?
181
+ type.is_a?(Symbol) ? type : Padrino::Inflections.demodulize(type).downcase.to_sym
182
+ end
183
+
147
184
  # Returns nil when the model is not defined. A model that failed to load keeps its error in
148
185
  # @load_error, whether looking it up raised it or loading the project (config/boot.rb) did.
149
186
  def load_klass
@@ -45,7 +45,7 @@
45
45
 
46
46
  <footer>
47
47
  <div class='footer-wrapper container'>
48
- <p class='pull-left'>Copyright &copy; <%= Time.now.year %> Your Site - Powered by Padrino v.<%= Padrino.version %></p>
48
+ <p class='pull-left'>Copyright &copy; <%%= Time.now.year %> Your Site - Powered by Padrino v.<%= Padrino.version %></p>
49
49
  <ul class='pull-right footer-links'>
50
50
  <li><%%= link_to tag_icon(:home, 'web'), 'http://www.padrinorb.com', target: :_blank, class: 'footer-links-link' %></li>
51
51
  <li><%%= link_to tag_icon(:heart, 'blog'), 'http://www.padrinorb.com/blog', target: :_blank, class: 'footer-links-link' %></li>
@@ -3,8 +3,8 @@
3
3
  <fieldset class='control-group <%%= error ? 'has-error' : ''%>'>
4
4
  <%%= f.label :<%= column[:name] %>, class: 'control-label' %>
5
5
  <div class='controls'>
6
- <%%= f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-xlarge input-with-feedback'<%- if (index == 0) -%>, autofocus: true<%- end -%> %>
7
- <span class='help-inline'><%%= error ? f.error_message_on(:<%= column[:name] %>) : 'Ex: a simple text' %></span>
6
+ <%%= f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-xlarge input-with-feedback'<%- if column[:step] -%>, step: '<%= column[:step] %>'<%- end -%><%- if (index == 0) -%>, autofocus: true<%- end -%> %>
7
+ <span class='help-inline'><%%= f.error_message_on(:<%= column[:name] %>) %></span>
8
8
  </div>
9
9
  </fieldset>
10
10
  <% end %>
@@ -3,9 +3,9 @@
3
3
  %fieldset.control-group{class: error ? 'has-error' : ''}
4
4
  =f.label :<%= column[:name] %>, class: 'control-label'
5
5
  .controls
6
- <% if column[:field_type] == :text_area %>~<% else %>=<% end %>f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-large input-with-feedback'<%- if (index == 0) -%>, autofocus: true<%- end -%>
6
+ <% if column[:field_type] == :text_area %>~<% else %>=<% end %>f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-large input-with-feedback'<%- if column[:step] -%>, step: '<%= column[:step] %>'<%- end -%><%- if (index == 0) -%>, autofocus: true<%- end -%>
7
7
 
8
- %span.help-inline=error ? f.error_message_on(:<%= column[:name] %>, class: 'text-error') : pat(:example)
8
+ %span.help-inline=f.error_message_on(:<%= column[:name] %>, class: 'text-error')
9
9
  <%- end -%>
10
10
 
11
11
  .form-actions
@@ -16,7 +16,7 @@
16
16
  if <%= @orm.save %>
17
17
  @title = pat(:create_title, model: "<%= @orm.name_singular %> #{@<%= @orm.name_singular %>.id}")
18
18
  flash[:success] = pat(:create_success, model: '<%= @orm.klass_name %>')
19
- params[:save_and_continue] ? redirect(url(:<%= @orm.name_plural %>, :index)) : redirect(url(:<%= @orm.name_plural %>, :edit, id: @<%= @orm.name_singular %>.id))
19
+ params[:save_and_continue] ? redirect(url(:<%= @orm.name_plural %>, :edit, id: @<%= @orm.name_singular %>.id)) : redirect(url(:<%= @orm.name_plural %>, :index))
20
20
  else
21
21
  @title = pat(:create_title, model: '<%= @orm.name_singular %>')
22
22
  flash.now[:error] = pat(:create_error, model: '<%= @orm.name_singular %>')
@@ -41,8 +41,8 @@
41
41
  if <%= @orm.update_attributes("params[:#{@orm.name_param}]") %>
42
42
  flash[:success] = pat(:update_success, model: '<%= @orm.name_singular.capitalize %>', id: params[:id])
43
43
  params[:save_and_continue] ?
44
- redirect(url(:<%= @orm.name_plural %>, :index)) :
45
- redirect(url(:<%= @orm.name_plural %>, :edit, id: @<%= @orm.name_singular %>.id))
44
+ redirect(url(:<%= @orm.name_plural %>, :edit, id: @<%= @orm.name_singular %>.id)) :
45
+ redirect(url(:<%= @orm.name_plural %>, :index))
46
46
  else
47
47
  flash.now[:error] = pat(:update_error, model: '<%= @orm.name_singular %>')
48
48
  render '<%= @orm.name_plural %>/edit'
@@ -3,9 +3,9 @@
3
3
  fieldset class='control-group#{error ? ' has-error' : ''}'
4
4
  = f.label :<%= column[:name] %>, class: 'control-label'
5
5
  div class='controls'
6
- = f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-large input-with-feedback'<%- if (index == 0) -%>, autofocus: true<%- end -%>
6
+ = f.<%= column[:field_type] %> :<%= column[:name] %>, class: 'form-control input-large input-with-feedback'<%- if column[:step] -%>, step: '<%= column[:step] %>'<%- end -%><%- if (index == 0) -%>, autofocus: true<%- end -%>
7
7
 
8
- span class='help-inline' = error ? f.error_message_on(:<%= column[:name] %>, class: 'text-error') : pat(:example)
8
+ span class='help-inline' = f.error_message_on(:<%= column[:name] %>, class: 'text-error')
9
9
  <%- end -%>
10
10
 
11
11
  div class="form-actions"
@@ -306,6 +306,32 @@ describe 'AdminAppGenerator' do
306
306
  end
307
307
  assert_empty out.lines.grep(/\ACOMMENT .*\[if /)
308
308
  end
309
+
310
+ it "should show the year of the request, not of the generation, in the #{engine} admin footer" do
311
+ skip 'the sqlite3 gem is only bundled on MRI' if RUBY_ENGINE == 'jruby'
312
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{engine}") }
313
+ Time.stubs(:now).returns(Time.new(2001, 2, 3))
314
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
315
+ Time.unstub(:now)
316
+ script = <<~'RUBY'
317
+ ENV['RACK_ENV'] = 'test'
318
+ %w[sequel haml slim erubi nokogiri rack/test].each { |lib| require lib }
319
+ Sequel.extension :migration
320
+ Sequel.sqlite('db/sample_project_test.db') { |db| Sequel::Migrator.run(db, 'db/migrate') }
321
+ require File.expand_path('config/boot')
322
+ account_id = Account.dataset.insert(email: 'admin@example.com', role: 'admin', crypted_password: 'unused')
323
+ browser = Rack::Test::Session.new(Padrino.application)
324
+ browser.env('rack.session', SampleProject::Admin.session_id => account_id)
325
+ browser.get('/admin/')
326
+ puts "YEAR #{Time.now.year}"
327
+ puts "FOOTER #{Nokogiri::HTML(browser.last_response.body).at_css('footer p')&.text.to_s.split.join(' ')}"
328
+ RUBY
329
+ env = { 'BUNDLE_GEMFILE' => File.expand_path('../../../Gemfile', __dir__) }
330
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: "#{@apptmp}/sample_project")
331
+ assert status.success?, err
332
+ footer = out[/^FOOTER (.*)$/, 1]
333
+ assert_includes footer, "Copyright \u00A9 #{out[/^YEAR (\d+)$/, 1]} "
334
+ end
309
335
  end
310
336
  end
311
337
 
@@ -1,6 +1,8 @@
1
1
  require_relative '../helper'
2
2
  require_relative '../fixtures/sequel'
3
+ require 'json'
3
4
  require 'nokogiri'
5
+ require 'open3'
4
6
  require 'padrino-gen/generators/cli'
5
7
 
6
8
  describe 'AdminPageGenerator' do
@@ -298,6 +300,146 @@ describe 'AdminPageGenerator' do
298
300
  Sequel::Model.db.drop_table?(:switches)
299
301
  end
300
302
  end
303
+
304
+ it "should generate a form with an input for each column type, no placeholder help, and Save back to the list (#{renderer})" do
305
+ skip 'the sqlite3 gem is only bundled on MRI' if RUBY_ENGINE == 'jruby'
306
+ # Without the fixture's Account, the admin generator adds the account model and its migration.
307
+ account = Object.send(:remove_const, :Account) if Object.const_defined?(:Account, false)
308
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{renderer}") }
309
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
310
+ project = "#{@apptmp}/sample_project"
311
+ File.write("#{project}/db/migrate/002_create_gadgets.rb", <<~'RUBY')
312
+ Sequel.migration do
313
+ up do
314
+ create_table :gadgets do
315
+ primary_key :id
316
+ String :name
317
+ Text :notes
318
+ Integer :quantity
319
+ Decimal :price
320
+ Float :weight
321
+ Date :released_on
322
+ DateTime :published_at
323
+ Time :opens_at, only_time: true
324
+ TrueClass :active
325
+ end
326
+ end
327
+ end
328
+ RUBY
329
+ File.write("#{project}/models/gadget.rb", "class Gadget < Sequel::Model; end\n")
330
+ db = Sequel.sqlite("#{project}/db/sample_project_test.db")
331
+ Sequel.extension :migration
332
+ Sequel::Migrator.run(db, "#{project}/db/migrate")
333
+ Object.const_set(:Gadget, Class.new(Sequel::Model(db[:gadgets])))
334
+ capture_io { generate(:admin_page, 'gadget', "--root=#{project}") }
335
+ script = <<~'RUBY'
336
+ ENV['RACK_ENV'] = 'test'
337
+ %w[json sequel haml slim erubi nokogiri rack/test].each { |lib| require lib }
338
+ require File.expand_path('config/boot')
339
+ account_id = Account.dataset.insert(email: 'admin@example.com', role: 'admin', crypted_password: 'unused')
340
+ browser = Rack::Test::Session.new(Padrino.application)
341
+ browser.env('rack.session', SampleProject::Admin.session_id => account_id)
342
+ page = lambda do |path|
343
+ browser.get(path)
344
+ raise "#{path} answered #{browser.last_response.status}" unless browser.last_response.status == 200
345
+ Nokogiri::HTML(browser.last_response.body)
346
+ end
347
+ inputs = lambda do |html|
348
+ html.css('form .controls input:not([type=hidden]), form .controls textarea').to_h do |input|
349
+ [input['name'][/\[(.*)\]/, 1], [input.name == 'textarea' ? 'textarea' : input['type'], input['step'], input['value']]]
350
+ end
351
+ end
352
+ location = ->(response) { URI(response['Location']).path }
353
+ attributes = { name: 'Widget', quantity: '7', price: '9.99', weight: '1.25', released_on: '2026-11-11',
354
+ published_at: '2026-11-11T10:30', opens_at: '09:15', active: '1' }
355
+ new_page = page.call('/admin/gadgets/new')
356
+ results = { 'new' => inputs.call(new_page), 'help' => new_page.css('.help-inline').map { |help| help.text.strip } }
357
+ browser.post('/admin/gadgets/create', gadget: attributes)
358
+ results['create'] = location.call(browser.last_response)
359
+ browser.post('/admin/gadgets/create', gadget: attributes, save_and_continue: 'Save and continue')
360
+ results['create and continue'] = location.call(browser.last_response)
361
+ browser.put('/admin/gadgets/update/1', gadget: { quantity: '8' })
362
+ results['update'] = location.call(browser.last_response)
363
+ browser.put('/admin/gadgets/update/1', gadget: { quantity: '9' }, save_and_continue: 'Save and continue')
364
+ results['update and continue'] = location.call(browser.last_response)
365
+ results['edit'] = inputs.call(page.call('/admin/gadgets/edit/1'))
366
+ puts "RESULTS #{JSON.generate(results)}"
367
+ RUBY
368
+ env = { 'BUNDLE_GEMFILE' => File.expand_path('../../../Gemfile', __dir__) }
369
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: project)
370
+ results = out[/^RESULTS (.*)$/, 1]
371
+ assert results, "#{status}\n#{out}\n#{err}"
372
+ results = JSON.parse(results)
373
+ types = results['new'].transform_values { |(type, step)| [type, step] }
374
+ assert_equal({ 'name' => ['text', nil], 'notes' => ['textarea', nil], 'quantity' => ['number', nil],
375
+ 'price' => %w[number any], 'weight' => %w[number any], 'released_on' => ['date', nil],
376
+ 'published_at' => ['datetime-local', nil], 'opens_at' => ['time', nil], 'active' => ['checkbox', nil] }, types)
377
+ assert_equal [''] * 9, results['help']
378
+ assert_equal '/admin/gadgets', results['create']
379
+ assert_equal '/admin/gadgets/edit/2', results['create and continue']
380
+ assert_equal '/admin/gadgets', results['update']
381
+ assert_equal '/admin/gadgets/edit/1', results['update and continue']
382
+ values = results['edit'].transform_values(&:last)
383
+ assert_equal '9', values['quantity']
384
+ assert_equal 9.99, Float(values['price'])
385
+ assert_equal '2026-11-11', values['released_on']
386
+ assert_equal '2026-11-11T10:30:00', values['published_at']
387
+ assert_equal '09:15:00.000', values['opens_at']
388
+ ensure
389
+ Object.send(:remove_const, :Gadget) if Object.const_defined?(:Gadget, false)
390
+ Object.send(:remove_const, :Account) if Object.const_defined?(:Account, false)
391
+ Object.const_set(:Account, account) if account
392
+ db&.disconnect
393
+ end
394
+ end
395
+
396
+ describe 'the form field of a column' do
397
+ def form_fields(orm, types)
398
+ columns = types.each_with_index.map { |type, index| Padrino::Admin::Generators::Orm::Column.new(:"column#{index}", type) }
399
+ Padrino::Admin::Generators::Orm.new('friend', orm, columns).column_fields.map { |column| [column[:field_type], column[:step]].compact }
400
+ end
401
+
402
+ def named_class(name)
403
+ Class.new.tap { |klass| klass.define_singleton_method(:to_s) { name } }
404
+ end
405
+
406
+ it 'should match the Active Record column type' do
407
+ types = %i[string text integer float decimal date datetime timestamptz time boolean binary]
408
+ expected = [[:text_field], [:text_area], [:number_field], [:number_field, 'any'], [:number_field, 'any'], [:date_field],
409
+ [:datetime_local_field], [:datetime_local_field], [:time_field], [:check_box], [:text_field]]
410
+ assert_equal expected, form_fields(:activerecord, types)
411
+ end
412
+
413
+ it 'should match the Mongoid field type, keeping a text field for times, which carry an offset' do
414
+ types = [String, Integer, Float, BigDecimal, Date, DateTime, Time, named_class('ActiveSupport::TimeWithZone'),
415
+ named_class('Mongoid::Boolean'), Object]
416
+ expected = [[:text_field], [:number_field], [:number_field, 'any'], [:number_field, 'any'], [:date_field],
417
+ [:text_field], [:text_field], [:text_field], [:check_box], [:text_field]]
418
+ assert_equal expected, form_fields(:mongoid, types)
419
+ end
420
+
421
+ it 'should match the Sequel column type when the model is not loaded' do
422
+ columns = %i[integer string].map { |type| Padrino::Admin::Generators::Orm::Column.new(type, type) }
423
+ fields = Padrino::Admin::Generators::Orm.new('not_loaded_model', :sequel, columns).column_fields.map { |column| column[:field_type] }
424
+ assert_equal %i[number_field text_field], fields
425
+ end
426
+
427
+ it 'should keep a text field for a Sequel enum column, whose reader returns a name' do
428
+ Object.const_set(:EnumGadget, Class.new(Sequel::Model(:friends)) do
429
+ plugin :enum
430
+ enum :age, { young: 1, old: 2 }
431
+ enum :name, { short: 1 }, override_accessors: false
432
+ end)
433
+ Object.const_set(:EnumGadgetPart, Class.new(EnumGadget))
434
+ columns = %i[age name email].map { |name| Padrino::Admin::Generators::Orm::Column.new(name, :integer) }
435
+ %w[enum_gadget enum_gadget_part].each do |model|
436
+ fields = Padrino::Admin::Generators::Orm.new(model, :sequel, columns).column_fields.map { |column| column[:field_type] }
437
+ assert_equal %i[text_field number_field number_field], fields, model
438
+ end
439
+ ensure
440
+ Object.send(:remove_const, :EnumGadgetPart) if Object.const_defined?(:EnumGadgetPart, false)
441
+ Object.send(:remove_const, :EnumGadget) if Object.const_defined?(:EnumGadget, false)
442
+ end
301
443
  end
302
444
 
303
445
  it 'should not carry a flash over to the next page when a record is not found' do
@@ -325,6 +467,123 @@ describe 'AdminPageGenerator' do
325
467
  Object.const_set(:SampleProject, saved) if saved
326
468
  end
327
469
 
470
+ it 'should keep a text field for an Active Record enum, whose value survives an edit and save' do
471
+ skip 'activerecord and sqlite3 are only bundled on MRI' if RUBY_ENGINE == 'jruby'
472
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=activerecord', '-e=erb') }
473
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
474
+ # Active Record is loaded in a separate process so that it stays out of the other tests.
475
+ script = <<~'RUBY'
476
+ require 'json'
477
+ require 'nokogiri'
478
+ require 'active_record'
479
+ require 'thor/group'
480
+ require 'padrino-admin'
481
+ require 'padrino-gen'
482
+ Padrino::Generators.load_components!
483
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
484
+ ActiveRecord::Schema.verbose = false
485
+ ActiveRecord::Schema.define do
486
+ create_table(:posts) { |t| t.string :title; t.integer :status; t.integer :views }
487
+ end
488
+ class Post < ActiveRecord::Base
489
+ enum :status, { draft: 0, published: 1 }
490
+ end
491
+ Padrino::Generators::AdminPage.start(%w[post -r=.])
492
+ module SampleProject
493
+ Admin = Sinatra.new(Padrino::Application) do
494
+ register Padrino::Helpers
495
+ enable :sessions
496
+ helpers Padrino::Admin::Helpers::ViewHelpers
497
+ set :views, File.expand_path('admin/views')
498
+ end
499
+ end
500
+ # The admin layout needs the whole admin app (accounts, sessions, project modules).
501
+ File.write('admin/views/layouts/application.erb', '<%= yield %>')
502
+ load 'admin/controllers/posts.rb'
503
+ browser = Rack::MockRequest.new(SampleProject::Admin)
504
+ id = Post.create!(title: 'kept', status: :published, views: 3).id
505
+ form = Nokogiri::HTML(browser.get("/posts/edit/#{id}").body)
506
+ fields = form.css('form input[name^="post["]').to_h { |input| [input['name'][/\[(.*)\]/, 1], [input['type'], input['value']]] }
507
+ # Submit the form unchanged, as a browser would.
508
+ response = browser.request('PUT', "/posts/update/#{id}", params: { 'post' => fields.transform_values(&:last) }, lint: true)
509
+ post = Post.find(id)
510
+ puts "RESULTS #{JSON.generate(fields: fields, status: response.status, saved: [post.title, post.status, post.views])}"
511
+ RUBY
512
+ env = { 'RACK_ENV' => 'test', 'BUNDLE_GEMFILE' => ENV['BUNDLE_GEMFILE'] || File.expand_path('../../../Gemfile', __dir__) }
513
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: "#{@apptmp}/sample_project")
514
+ results = out[/^RESULTS (.*)$/, 1]
515
+ assert results, "#{status}\n#{out}\n#{err}"
516
+ results = JSON.parse(results)
517
+ assert_equal({ 'title' => %w[text kept], 'status' => %w[text published], 'views' => %w[number 3] }, results['fields'])
518
+ assert_equal 303, results['status']
519
+ assert_equal ['kept', 'published', 3], results['saved']
520
+ end
521
+
522
+ it 'should answer a missing record with 404 and still find existing ones with activerecord' do
523
+ skip 'activerecord and sqlite3 are only bundled on MRI' if RUBY_ENGINE == 'jruby'
524
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=activerecord', '-e=erb') }
525
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
526
+ # Active Record is loaded in a separate process so that it stays out of the other tests.
527
+ # Entry has a primary key other than id.
528
+ script = <<~'RUBY'
529
+ require 'json'
530
+ require 'active_record'
531
+ require 'thor/group'
532
+ require 'padrino-admin'
533
+ Padrino::Generators.load_components!
534
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
535
+ ActiveRecord::Schema.verbose = false
536
+ ActiveRecord::Schema.define do
537
+ create_table(:posts) { |t| t.string :title }
538
+ create_table(:entries, id: false) { |t| t.primary_key :code; t.string :title }
539
+ end
540
+ class Post < ActiveRecord::Base; end
541
+ class Entry < ActiveRecord::Base
542
+ self.primary_key = 'code'
543
+ end
544
+ Padrino::Generators::AdminPage.start(%w[post entry -r=.])
545
+ module SampleProject
546
+ Admin = Sinatra.new(Padrino::Application) do
547
+ register Padrino::Helpers
548
+ enable :sessions
549
+ helpers Padrino::Admin::Helpers::ViewHelpers
550
+ set :views, File.expand_path('admin/views')
551
+ end
552
+ end
553
+ # The admin layout needs the whole admin app (accounts, sessions, project modules).
554
+ File.write('admin/views/layouts/application.erb', '<%= yield %>')
555
+ load 'admin/controllers/posts.rb'
556
+ load 'admin/controllers/entries.rb'
557
+ browser = Rack::MockRequest.new(SampleProject::Admin)
558
+ status = lambda do |verb, path, params = {}|
559
+ browser.request(verb, path, params: params, lint: true).status
560
+ rescue StandardError => e
561
+ "#{e.class.name}: #{e.message}"
562
+ end
563
+ results = {}
564
+ { 'posts' => [Post, 'post'], 'entries' => [Entry, 'entry'] }.each do |plural, (model, param)|
565
+ id = model.create!(title: 'kept').id
566
+ results[plural] = [
567
+ status.call('GET', "/#{plural}/edit/#{id}"),
568
+ status.call('PUT', "/#{plural}/update/#{id}", param => { title: 'changed' }),
569
+ model.find(id).title,
570
+ status.call('GET', "/#{plural}/edit/999"),
571
+ status.call('PUT', "/#{plural}/update/999"),
572
+ status.call('DELETE', "/#{plural}/destroy/999"),
573
+ status.call('DELETE', "/#{plural}/destroy/#{id}"),
574
+ model.exists?(id)
575
+ ]
576
+ end
577
+ puts "RESULTS #{JSON.generate(results)}"
578
+ RUBY
579
+ env = { 'RACK_ENV' => 'test', 'BUNDLE_GEMFILE' => ENV['BUNDLE_GEMFILE'] || File.expand_path('../../../Gemfile', __dir__) }
580
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: "#{@apptmp}/sample_project")
581
+ results = out[/^RESULTS (.*)$/, 1]
582
+ assert results, "#{status}\n#{out}\n#{err}"
583
+ expected = [200, 303, 'changed', 404, 404, 404, 303, false]
584
+ assert_equal({ 'posts' => expected, 'entries' => expected }, JSON.parse(results))
585
+ end
586
+
328
587
  it 'should correctly generate a new padrino admin application with multiple models at the same time' do
329
588
  capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel', '-e=haml') }
330
589
  capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
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.6
4
+ version: 0.18.7
5
5
  platform: ruby
6
6
  authors:
7
7
  - Padrino Team
@@ -19,28 +19,28 @@ dependencies:
19
19
  requirements:
20
20
  - - '='
21
21
  - !ruby/object:Gem::Version
22
- version: 0.18.6
22
+ version: 0.18.7
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.6
29
+ version: 0.18.7
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.6
36
+ version: 0.18.7
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.6
43
+ version: 0.18.7
44
44
  description: Admin View for Padrino applications
45
45
  email: padrinorb@gmail.com
46
46
  executables: []