Class: Hancock::Cms::SetupGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/hancock/cms/setup_generator.rb

Instance Method Summary collapse

Instance Method Details

#app_nameObject



483
484
485
# File 'lib/generators/hancock/cms/setup_generator.rb', line 483

def app_name
  Rails.application.class.parent_name
end

#ask_with_timeout(question, timeout = 5) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/generators/hancock/cms/setup_generator.rb', line 10

def ask_with_timeout(question, timeout = 5)
  ask(question)
  # # temp
  # begin
  #   Timeout::timeout(timeout) {
  #     ask("#{question} | U have only #{timeout} second(s)!")
  #   }
  # rescue
  #   puts ""
  #   ""
  # end
end

#installObject



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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/generators/hancock/cms/setup_generator.rb', line 8

def install

  def ask_with_timeout(question, timeout = 5)
    ask(question)
    # # temp
    # begin
    #   Timeout::timeout(timeout) {
    #     ask("#{question} | U have only #{timeout} second(s)!")
    #   }
    # rescue
    #   puts ""
    #   ""
    # end
  end

####### DEVISE #######

generate "devise:install" if ["yes", "y"].include?(ask_with_timeout("generate `devise:install`?(y or yes)").downcase.strip)
gsub_file 'config/initializers/devise.rb', "'[email protected]'", "'noreply@#{app_name.dasherize.downcase}.ru'"

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's layout for devise? (y or yes)").downcase.strip)
_sessions_layout      = Devise::SessionsController._layout       == "hancock/devise/sessions"
_registration_layout  = Devise::RegistrationsController._layout  == "hancock/devise/registrations"
_confirmations_layout = Devise::ConfirmationsController._layout  == "hancock/devise/confirmations"
_unlocks_layout       = Devise::UnlocksController._layout        == "hancock/devise/unlocks"
_passwords_layout     = Devise::PasswordsController._layout      == "hancock/devise/passwords"
if !_sessions_layout or !_registration_layout or !_confirmations_layout or !_unlocks_layout or !_passwords_layout
inject_into_file 'config/initializers/devise.rb', after: /^end/ do <<-TEXT

Rails.application.config.to_prepare do
  #{'Devise::SessionsController.layout        "hancock/devise/sessions"'      unless _sessions_layout }
  #{'Devise::RegistrationsController.layout   "hancock/devise/registrations"' unless _registration_layout }
  #{'Devise::ConfirmationsController.layout   "hancock/devise/confirmations"' unless _confirmations_layout }
  #{'Devise::UnlocksController.layout         "hancock/devise/unlocks"'       unless _unlocks_layout }
  #{'Devise::PasswordsController.layout       "hancock/devise/passwords"'     unless _passwords_layout }
end
TEXT
end
end
end
generate "devise", "User", "--routes=false" if ["yes", "y"].include?(ask_with_timeout("generate `devise User --routes=false`?(y or yes)").downcase.strip)


####### ROUTES #######


if ["yes", "y"].include?(ask_with_timeout("Set Hancock's routes? (y or yes)").downcase.strip)
remove_file 'config/routes.rb'
create_file 'config/routes.rb' do <<-TEXT
Rails.application.routes.draw do
  devise_for :users, controllers: {sessions: 'hancock/sessions'}
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  hancock_cms_routes
end
TEXT
end
end


####### INITIALIZERS #######

add_assets_precompiled = ["*.svg", 'ckeditor/*', 'codemirror.js', 'codemirror.css', 'codemirror/**/*']
if (Rails.application.config.assets.precompile & add_assets_precompiled).length < add_assets_precompiled.length
inject_into_file 'config/initializers/assets.rb', before: /\z/ do <<-TEXT
Rails.application.config.assets.precompile += %w( *.svg )
Rails.application.config.assets.precompile += %w( ckeditor/* )
Rails.application.config.assets.precompile += %w( codemirror.js codemirror.css codemirror/**/* )
TEXT
end
end


if mongoid
if defined?(Paperclip)
generate "ckeditor:install", "--orm=mongoid", "--backend=paperclip" if ["yes", "y"].include?(ask_with_timeout("generate `ckeditor:install --orm=mongoid --backend=paperclip`?(y or yes)").downcase.strip)
require 'ckeditor/orm/mongoid'
require Rails.root.join("app", "models", "ckeditor", "asset.rb")
if defined?(Ckeditor::Asset)
unless Ckeditor::Asset < Hancock::Model
inject_into_file 'app/models/ckeditor/asset.rb', before: /^end/ do <<-TEXT
  include Hancock::Model
TEXT
end
end
end
if ["yes", "y"].include?(ask_with_timeout("Set Hancock's config for Ckeditor::Picture? (y or yes)").downcase.strip)
remove_file 'app/models/ckeditor/picture.rb'
create_file 'app/models/ckeditor/picture.rb' do <<-TEXT
class Ckeditor::Picture < Ckeditor::Asset
  # has_mongoid_attached_file :data,
  #                           url: '/ckeditor_assets/pictures/:id/:style_:basename.:extension',
  #                           path: ':rails_root/public/ckeditor_assets/pictures/:id/:style_:basename.:extension',
  #                           styles: { content: '800>', thumb: '118x100#' }

  include Hancock::Gallery::Paperclipable
  hancock_cms_attached_file :data,
                        url: '/ckeditor_assets/pictures/:id/:style/:basename.:extension',
                        path: ':rails_root/public/ckeditor_assets/pictures/:id/:style/:basename.:extension'
  def data_styles
if data_svg?
  {}
else
  { content: '800>', thumb: '118x100#' }
end
  end

  validates_attachment_size :data, less_than: 2.megabytes
  validates_attachment_presence :data
  validates_attachment_content_type :data, content_type: /\\Aimage/

  def url_content
# url(:content)
if data_svg?
  url
else
  url(:content)
end
  end

  def url_thumb
# url(:thumb)
if data_svg?
  url
else
  url(:thumb)
end
  end
end
TEXT
end
end
end

else
if defined?(Paperclip)
  generate "ckeditor:install", "--orm=active_record", "--backend=paperclip" if ["yes", "y"].include?(ask_with_timeout("generate `ckeditor:install --orm=active_record --backend=paperclip`?(y or yes)").downcase.strip)
end
end
if File.exists?(Rails.root.join 'config/initializers/ckeditor.rb')
  gsub_file 'config/initializers/ckeditor.rb', "# config.image_file_types = %w(jpg jpeg png gif tiff)", "config.image_file_types = %w(jpg jpeg png gif tiff svg)"
  gsub_file 'config/initializers/ckeditor.rb', "# config.authorize_with :cancan",                       "# config.authorize_with :cancancan"
  gsub_file 'config/initializers/ckeditor.rb', "# config.assets_languages = ['en', 'uk']",              "config.assets_languages = ['en', 'ru']"
end

if mongoid and ["yes", "y"].include?(ask_with_timeout("Set Hancock's config for cookies_serializer? (y or yes)").downcase.strip)
remove_file 'config/initializers/cookies_serializer.rb'
create_file 'config/initializers/cookies_serializer.rb' do  <<-TEXT
# Be sure to restart your server when you modify this file.
# json serializer breaks Devise + Mongoid. DO NOT ENABLE
# See https://github.com/plataformatec/devise/pull/2882
# Rails.application.config.action_dispatch.cookies_serializer = :json
Rails.application.config.action_dispatch.cookies_serializer = :marshal
TEXT
end
end

gsub_file 'config/initializers/filter_parameter_logging.rb', "[:password]", "[:password, :password_confirmation]"

# generate 'paperclip_optimizer:install'
# remove_file 'config/initializers/paperclip_optimizer.rb'
generate "hancock:cms:paperclip_optimizer" if ["yes", "y"].include?(ask_with_timeout("generate `hancock:cms:paperclip_optimizer`? (y or yes)").downcase.strip)

# generate 'rails_email_preview:install'
# remove_file 'app/mailer_previews/contact_mailer_preview.rb'
# create_file 'app/mailer_previews/contact_mailer_preview.rb' do <<-TEXT
# class ContactMailerPreview
#   def new_message_email
#     Hancock::Feedback::ContactMailer.new_message_email(Hancock::Feedback::ContactMessage.all.to_a.sample)
#   end
# end
# TEXT
# end

generate "hancock:cms:config" if ["yes", "y"].include?(ask_with_timeout("generate `hancock:cms:config`? (y or yes)").downcase.strip)

generate "hancock:cms:rack" if ["yes", "y"].include?(ask_with_timeout("generate `hancock:cms:rack`? (y or yes)").downcase.strip)

generate "hancock:cms:admin" if ["yes", "y"].include?(ask_with_timeout("generate `hancock:cms:admin`? (y or yes)").downcase.strip)

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's config for session_store? (y or yes)").downcase.strip)
remove_file 'config/initializers/session_store.rb'
if mongoid
create_file 'config/initializers/session_store.rb' do  <<-TEXT
# Be sure to restart your server when you modify this file.

#Rails.application.config.session_store :cookie_store, key: '_#{app_name.tableize.singularize}_session'
Rails.application.config.session_store :mongoid_store
TEXT
end
else
generate 'active_record_store:session_migration'
create_file 'config/initializers/session_store.rb' do  <<-TEXT
# Be sure to restart your server when you modify this file.

#Rails.application.config.session_store :cookie_store, key: '_#{app_name.tableize.singularize}_session'
Rails.application.config.session_store :active_record_store
TEXT
end
end
end

# unless mongoid
#   generate 'simple_captcha'
# end

generate "simple_form:install" if ["yes", "y"].include?(ask_with_timeout("generate `simple_form:install`? (y or yes)").downcase.strip)



####### CONTROLLERS #######


unless ApplicationController < Hancock::Controller
remove_file 'app/controllers/application_controller.rb'
create_file 'app/controllers/application_controller.rb' do <<-TEXT
class ApplicationController < ActionController::Base
  include Hancock::Controller
end
TEXT
end
end


####### MODELS #######

generate "hancock:cms:ability" if ["yes", "y"].include?(ask_with_timeout("generate `hancock:cms:ability`? (y or yes)").downcase.strip)

gsub_user_rb = begin
  (User < Hancock::Model).nil?
rescue
  true
end
if gsub_user_rb
gsub_file 'app/models/user.rb', '# :confirmable, :lockable, :timeoutable and :omniauthable' do <<-TEXT
include Hancock::Model
  include Hancock::Enableable
  include Hancock::RailsAdminPatch
  def self.manager_can_default_actions
[:show, :read]
  end
  def self.manager_cannot_actions
[:new, :create, :delete, :destroy]
  end

  ######################### RailsAdminUserAbilities #########################
  # def self.rails_admin_user_defined_visible_actions
  #   [:user_abilities]
  # end
  # has_one :ability, class_name: "RailsAdminUserAbilities::UserAbility", as: :rails_admin_user_abilitable
  # scope :for_rails_admin, -> { where(:roles.in => ['admin', 'manager']) } # could be any you want, just need to
  ###########################################################################

  cattr_accessor :current_user

  # Include default devise modules. Others available are:
  # :confirmable,  :lockable, :timeoutable and :omniauthable
TEXT
end

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's User model? (y or yes)").downcase.strip)
gsub_file 'app/models/user.rb', ':registerable,', ' :lockable,'
if mongoid
gsub_file 'app/models/user.rb', '# field :failed_attempts', 'field :failed_attempts'
gsub_file 'app/models/user.rb', '# field :unlock_token', 'field :unlock_token'
gsub_file 'app/models/user.rb', '# field :locked_at', 'field :locked_at'

inject_into_file 'app/models/user.rb', before: /^end/ do <<-TEXT

  field :name,    type: String
  field :login,   type: String
  field :roles,   type: Array, default: []

  before_save do
self.roles ||= []
self.roles.reject! { |r| r.blank? }
  end

  AVAILABLE_ROLES = ["admin", "manager", "client"].freeze

  AVAILABLE_ROLES.each do |r|
class_eval <<-RUBY
  def \#{r}?
    self.roles and self.roles.include?("\#{r}")
  end

  scope :\#{r.pluralize}, -> { any_in(roles: "\#{r}") }
RUBY
  end

  def self.generate_first_admin_user
if ::User.admins.all.count == 0
  _email_pass = 'admin@#{app_name.dasherize.downcase}.ru'
  if ::User.new(roles: ["admin"], email: _email_pass, password: _email_pass, password_confirmation: _email_pass).save
    puts "#################################################################################"
    puts "#################################################################################"
    puts "AdminUser with email and password '\#{_email_pass}' was created!"
    puts "#################################################################################"
    puts "#################################################################################"
  else
    puts 'Creating AdminUser error'
  end
else
  puts 'AdminUsers are here already'
end
  end

  def self.generate_first_manager_user
if ::User.managers.all.count == 0
  _email_pass = 'manager@#{app_name.dasherize.downcase}.ru'
  if ::User.create(roles: ["manager"], email: _email_pass, password: _email_pass, password_confirmation: _email_pass)
    puts "ManagerUser with email and password '\#{_email_pass}' was created!"
  else
    puts 'Creating ManagerUser error'
  end
else
  puts 'ManagerUsers are here already'
end
  end

  rails_admin do
navigation_icon 'icon-user'
list do
  field :email
  field :name
  field :login
  field :roles do
    pretty_value do
      render_object = (bindings[:controller] || bindings[:view])
      render_object.content_tag(:p, bindings[:object].roles.join(", ")) if render_object
    end
  end
end

edit do
  group :login do
    active false
    field :email, :string do
      visible do
        render_object = (bindings[:controller] || bindings[:view])
        render_object and (render_object.current_user.admin? or (render_object.current_user.manager? and render_object.current_user == bindings[:object]))
      end
    end
    field :name, :string
    field :login, :string do
      visible do
        render_object = (bindings[:controller] || bindings[:view])
        render_object and render_object.current_user.admin?
      end
    end
  end

  group :roles do
    active false
    field :roles, :hancock_enum do
      enum do
        ::User::AVAILABLE_ROLES
      end

      multiple do
        true
      end

      visible do
        render_object = (bindings[:controller] || bindings[:view])
        render_object and render_object.current_user.admin?
      end
    end
  end

  group :password do
    active false
    field :password do
      visible do
        render_object = (bindings[:controller] || bindings[:view])
        render_object and (render_object.current_user.admin? or render_object.current_user == bindings[:object])
      end
    end
    field :password_confirmation do
      visible do
        render_object = (bindings[:controller] || bindings[:view])
        render_object and (render_object.current_user.admin? or render_object.current_user == bindings[:object])
      end
    end
  end
end

  end
TEXT
end
end
end
end


###### HANCOCK OTHERS ######

unless mongoid
generate "hancock:cms:migration"
generate "rails_admin_settings:migration"
end

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's layout? (y or yes)").downcase.strip)
remove_file 'app/views/layouts/application.html.erb'
generate "hancock:cms:layout"
end

run 'rails r "User.generate_first_admin_user"'

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's assets? (y or yes)").downcase.strip)
remove_file 'app/assets/stylesheets/application.css'
remove_file 'app/assets/javascripts/application.js'
generate "hancock:cms:assets", app_name
end

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's robots.txt? (y or yes)").downcase.strip)
remove_file 'public/robots.txt'
generate "hancock:cms:robots", app_name
end

if ["yes", "y"].include?(ask_with_timeout("Set Hancock's unicorn config? (y or yes)").downcase.strip)
#god+unicorn
generate "hancock:cms:unicorn_god", app_name
end
if ["yes", "y"].include?(ask_with_timeout("Set Hancock's scripts? (y or yes)").downcase.strip)
#scripts
generate "hancock:cms:scripts", app_name
end

FileUtils.cp(Pathname.new(destination_root).join('config', 'secrets.yml').to_s, Pathname.new(destination_root).join('config', 'secrets.yml.example').to_s)

unless mongoid
generate "paper_trail:install"
generate "friendly_id"
rake "db:migrate"
end

generate "rspec:install" if ["yes", "y"].include?(ask_with_timeout("generate `rspec:install`? (y or yes)").downcase.strip)


####### GIT #######

remove_file '.gitignore'
create_file '.gitignore' do <<-TEXT
# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile '~/.gitignore_global'
.idea
.idea/*

/.bundle
/log/*.log
/tmp/*
/public/assets
# /public/ckeditor_assets
Gemfile.lock
TEXT
end

create_file 'extra/.gitkeep', ''


if ["yes", "y"].include?(ask_with_timeout("Do u want init git? (y or yes)").downcase.strip)
git :init
git add: "."
git commit: %Q{ -m 'Initial commit' }
end

end

#mongoidObject



479
480
481
# File 'lib/generators/hancock/cms/setup_generator.rb', line 479

def mongoid
  !!defined? Mongoid
end