Class: InlineForms::Creator

Inherits:
Thor
  • Object
show all
Includes:
Thor::Actions
Defined in:
bin/inline_forms

Constant Summary collapse

DATABASE_OPTIONS =
%w(sqlite mysql)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.databaseObject



49
50
51
# File 'bin/inline_forms', line 49

def self.database
  DATABASE_OPTIONS.include?(options[:database]) ? options[:database] : 'sqlite'
end

.dry_run?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'bin/inline_forms', line 41

def self.dry_run?
  options[:dry]
end

.emailObject



57
58
59
# File 'bin/inline_forms', line 57

def self.email
  options[:email]
end

.install_example?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'bin/inline_forms', line 45

def self.install_example?
  options[:example]
end

.passwordObject



61
62
63
# File 'bin/inline_forms', line 61

def self.password
  options[:password]
end

.source_rootObject



27
28
29
# File 'bin/inline_forms', line 27

def self.source_root
  File.dirname(__FILE__)+"/.."
end

.using_sqlite?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'bin/inline_forms', line 53

def self.using_sqlite?
  database == 'sqlite'
end

Instance Method Details

#create(app_name) ⇒ Object



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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'bin/inline_forms', line 39

def create(app_name)

  def self.dry_run?
    options[:dry]
  end

  def self.install_example?
    options[:example]
  end

  def self.database
    DATABASE_OPTIONS.include?(options[:database]) ? options[:database] : 'sqlite'
  end
  
  def self.using_sqlite?
    database == 'sqlite'
  end

  def self.email
    options[:email]
  end

  def self.password
    options[:password]
  end

  if install_example? && dry_run?
    say "--example and --dry-run can not be used together", :red
    exit 1
  end

  if install_example? && !using_sqlite?
    say "--example can only be used with an sqlite development database", :red
    exit 1
  end

  say "This is a dry run. I hope you know what you are doing...", :red if dry_run?

  say "Creating #{app_name} with inline_forms v#{VERSION} and development database #{database}...", :green

  regex = /\A[0-9a-zA-Z][0-9a-zA-Z_-]+[0-9a-zA-Z]\Z/
  if ! regex.match(app_name)
    say "Error: APP must match #{regex.source}", :red
    exit 1
  end

  if File.exists?(app_name)
    say "Error: APP exists", :red
    exit 1
  end

  if dry_run?
    empty_directory(app_name)
  else
    if ! run("rails new #{app_name} --skip-bundle --skip-gemfile --skip-test-unit")
      say "Rails could not create the app '#{app_name}', maybe because it is a reserved word...", :red
      exit 1
    end
  end

  ruby_version = (%x[rvm current]).gsub(/@.*/,'')
  create_file "#{app_name}/.ruby-version", "#{ruby_version.chop}@#{app_name}"

  say "chdir: '#{app_name}'...", :green
  RVM.chdir(app_name) do
    RVM.gemset_use! app_name
    say "- Working directory is now #{`pwd`}"
    say "- RVM gemset is now #{%x[rvm current]}"
  
    create_file "#{app_name}/Gemfile", <<-END_GEMFILE.strip_heredoc_with_indent
      # generated by inline_forms v#{VERSION}

      source 'http://rubygems.org'

      gem 'rails', '3.2.12'
      gem 'rake', '10.0.4'
      gem 'jquery-rails', '~> 2.3.0'
      gem 'jquery-ui-rails'
      gem 'capistrano'
      gem 'will_paginate', :git => 'git://github.com/acesuares/will_paginate.git'
      gem 'tabs_on_rails', :git => 'git://github.com/acesuares/tabs_on_rails.git', :branch => 'update_remote'
      gem 'ckeditor'
      gem 'cancan', :git => 'git://github.com/acesuares/cancan.git', :branch => '2.0'
      gem 'carrierwave'
      gem 'remotipart', '~> 1.0'
      gem 'paper_trail'
      gem 'devise'
      gem 'inline_forms'
      gem 'validation_hints'
      gem 'mini_magick'
      gem 'jquery-ui-rails'
      gem 'yaml_db'
      gem 'rails-i18n', '~> 3.0.0'
      gem 'i18n-active_record', :git => 'git://github.com/acesuares/i18n-active_record.git'
      gem 'unicorn'
      gem 'rvm'
      gem 'rvm-capistrano'

      # Include everything needed to run rake, tests, features, etc.
      group :development do
        gem 'sqlite3'
        gem 'rspec-rails'
        gem 'shoulda', '>= 0'
        gem 'bundler'
        gem 'jeweler'
        # gem 'rcov', '>= 0'
      end

     # these are just for production
     group :production do
       gem 'mysql2'
       gem 'therubyracer'
       gem 'uglifier', '>= 1.0.3'
     end

     group :assets do
       gem 'sass-rails',   '~> 3.2.3'
       gem 'coffee-rails', '~> 3.2.1'
       gem 'uglifier', '>= 1.0.3'
       gem 'compass-rails' # you need this or you get an err
       gem 'zurb-foundation', '~> 4.0.0'
    end 
    END_GEMFILE

    say "- Running bundle..."
    run("bundle") unless dry_run?
  
    say "- Database setup: creating config/database.yml with development database #{database}"
    remove_file "#{app_name}/config/database.yml" # the one that 'rails _3.2.12_ new' created
    if using_sqlite?
      create_file "#{app_name}/config/database.yml", <<-END_DATABASEYML.strip_heredoc_with_indent
      development:
        adapter: sqlite3
        database: db/development.sqlite3
        pool: 5
        timeout: 5000

      END_DATABASEYML
    else
      create_file "#{app_name}/config/database.yml", <<-END_DATABASEYML.strip_heredoc_with_indent
      development:
        adapter: mysql2
        database: #{app_name}_dev
        username: #{app_name}
        password: #{app_name}

      END_DATABASEYML
    end
    append_file "#{app_name}/config/database.yml", <<-END_DATABASEYML.strip_heredoc_with_indent
      production:
        adapter: mysql2
        database: #{app_name}_p
        username: #{app_name}
        password: #{app_name}444
    END_DATABASEYML

    say "- Devise install..."
    run "bundle exec rails g devise:install" unless dry_run?

    say "- Devise User model install with added name and locale field..."
    run "bundle exec rails g devise User name:string locale:string" unless dry_run?

    say "- Replace Devise route and add path_prefix..."
    gsub_file "#{app_name}/config/routes.rb", /devise_for :users/, "devise_for :users, :path_prefix => 'auth'"
    insert_into_file "#{app_name}/config/routes.rb", <<-ROUTE.strip_heredoc_with_indent(2), :after => "devise_for :users, :path_prefix => 'auth'\n"
      resources :users do
        post 'revert', :on => :member
      end
    ROUTE

    say "- Mount Ckeditor::Engine to routes..."
    insert_into_file "#{app_name}/config/routes.rb", "\nmount Ckeditor::Engine => \"/ckeditor\"\n", :after => "routes.draw do\n"

    say "- Create User Controller..."
    create_file "#{app_name}/app/controllers/users_controller.rb", <<-USERS_CONTROLLER.strip_heredoc_with_indent
      class UsersController < InlineFormsController
        set_tab :user
      end
    USERS_CONTROLLER

    say "- Recreate User Model..."
    remove_file "#{app_name}/app/models/user.rb" # the one that 'devise:install' created
    create_file "#{app_name}/app/models/user.rb", <<-USER_MODEL.strip_heredoc_with_indent
      class User < ActiveRecord::Base

        # devise options
        devise :database_authenticatable
        # devise :registerable # uncomment this if you want people to be able to register
        devise :recoverable
        devise :rememberable
        devise :trackable
        devise :validatable
        # devise :token_authenticatable
        # devise :confirmable,
        # devise :lockable
        # devise :timeoutable
        # devise :omniauthable

        # Setup accessible (or protected) attributes for your model
        attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :locale
        attr_writer :inline_forms_attribute_list

        # validations
        validates :name, :presence => true

        # pagination
        attr_reader :per_page
        @per_page = 7

        has_paper_trail

        def _presentation
          "\#{name}"
        end

        def inline_forms_attribute_list
          @inline_forms_attribute_list ||= [
            [ :name , 'name', :text_field ],
            [ :email , 'email', :text_field ],
            [ :password , 'Nieuw wachtwoord', :devise_password_field ],
            [ :encrypted_password , 'encrypted_password', :info ],
            [ :reset_password_token , 'reset_password_token', :info ],
            [ :reset_password_sent_at , 'reset_password_sent_at', :info],
            [ :remember_created_at , 'remember_created_at', :info ],
            [ :sign_in_count , 'sign_in_count', :info ],
            [ :current_sign_in_at , 'current_sign_in_at', :info ],
            [ :last_sign_in_at , 'last_sign_in_at', :info ],
            [ :current_sign_in_ip , 'current_sign_in_ip', :info ],
            [ :last_sign_in_ip , 'last_sign_in_ip', :info ],
            [ :created_at , 'created_at', :info ],
            [ :updated_at , 'updated_at', :info ],
          ]
        end

        def self.not_accessible_through_html?
          false
        end

        def self.order_by_clause
          'name'
        end

      end
    USER_MODEL

    #        say "- Install ckeditor/carrierwave..."
    #        run "bundle exec rails generate ckeditor:install --orm=active_record --backend=carrierwave" unless dry_run?

    say "- Create ckeditor config.js"
    copy_file "lib/app/assets/javascripts/ckeditor/config.js", "#{app_name}/app/assets/javascripts/ckeditor/config.js"

    say "- Add remotipart to application.js..."
    create_file "#{app_name}/app/assets/javascripts/application.js", "//= require_tree .\n" if dry_run?
    insert_into_file "#{app_name}/app/assets/javascripts/application.js", "//= require jquery.remotipart\n", :before => "//= require_tree .\n"

    say "- Add ckeditor to application.js..."
    insert_into_file "#{app_name}/app/assets/javascripts/application.js", "//= require ckeditor/init\n", :before => "//= require_tree .\n"

    say "- Paper_trail install..."
    run "bundle exec rails g paper_trail:install" unless dry_run?

    say "- Installaing ZURB Foundation..."
    run "bundle exec rails g foundation:install"

    say "- Generate models and tables and views for translations..."
    run 'bundle exec rails g inline_forms InlineFormsLocale name:string inline_forms_translations:belongs_to _enabled:yes _presentation:\'#{name}\''
    run 'bundle exec rails g inline_forms InlineFormsKey name:string inline_forms_translations:has_many inline_forms_translations:associated _enabled:yes _presentation:\'#{name}\''
    run 'bundle exec rails g inline_forms InlineFormsTranslation inline_forms_key:belongs_to inline_forms_locale:dropdown value:text interpolations:text is_proc:boolean _presentation:\'#{value}\''

    sleep 1 # to get unique migration number
    create_file "#{app_name}/db/migrate/" + 
      Time.now.utc.strftime("%Y%m%d%H%M%S") +
      "_" +
      "inline_forms_create_view_for_translations.rb", <<-VIEW_MIGRATION.strip_heredoc_with_indent
      class InlineFormsCreateViewForTranslations < ActiveRecord::Migration

        def self.up
          execute 'CREATE VIEW translations
                   AS
                     SELECT L.name AS locale,
                            K.name AS thekey,
                            T.value AS value,
                            T.interpolations AS interpolations,
                            T.is_proc AS is_proc
                       FROM inline_forms_keys K, inline_forms_locales L, inline_forms_translations T
                         WHERE T.inline_forms_key_id = K.id AND T.inline_forms_locale_id = L.id '
        end

        def self.down
          execute 'DROP VIEW translations'
        end

      end
    VIEW_MIGRATION
    
    say "- Migrating Database"
    run "bundle exec rake db:migrate" unless (dry_run? || !using_sqlite?)

    say "- Adding admin user with email: #{email}, password: #{password} to seeds.rb"
    append_to_file "#{app_name}/db/seeds.rb", "User.new({ :email => '#{email}', :name => 'Admin', :password => '#{password}', :password_confirmation => '#{password}'}).save"

    say "- Seeding the database"
    run "bundle exec rake db:seed" unless (dry_run? || !using_sqlite?)

    say "- Creating header in app/views/inline_forms/_header.html.erb..."
    create_file "#{app_name}/app/views/inline_forms/_header.html.erb", <<-END_HEADER.strip_heredoc_with_indent
        <div id='Header'>
          <div id='title'>
            #{app_name} v<%= inline_forms_version -%>
          </div>
          <% if current_user -%>
          <div id='logout'>
            <%= link_to \"Afmelden: \#{current_user.name}\", destroy_user_session_path, :method => :delete %>
          </div>
          <% end -%>
          <div style='clear: both;'></div>
        </div>
    END_HEADER

    say "- Recreating ApplicationHelper to set application_name and application_title..."
    remove_file "#{app_name}/app/helpers/application_helper.rb" # the one that 'rails new' created
    create_file "#{app_name}/app/helpers/application_helper.rb", <<-END_APPHELPER.strip_heredoc_with_indent
      module ApplicationHelper
        def application_name
          '#{app_name}'
        end
        def application_title
          '#{app_name}'
        end
      end
    END_APPHELPER

    say "- Recreating ApplicationController to add devise, cancan, I18n stuff..."
    remove_file "#{app_name}/app/controllers/application_controller.rb" # the one that 'rails new' created
    create_file "#{app_name}/app/controllers/application_controller.rb", <<-END_APPCONTROLLER.strip_heredoc_with_indent
      class ApplicationController < InlineFormsApplicationController
        protect_from_forgery

        # Comment next two lines if you don't want Devise authentication
        before_filter :authenticate_user!
        layout 'devise' if :devise_controller?

        # Comment next 6 lines if you want CanCan authorization
        enable_authorization :unless => :devise_controller?

        rescue_from CanCan::Unauthorized do |exception|
          sign_out :user if user_signed_in?
          redirect_to new_user_session_path, :alert => exception.message
        end

        # Uncomment next line if you want I18n (based on subdomain)
        # before_filter :set_locale

        # Uncomment next line and specify default locale
        # I18n.default_locale = :en

        # Uncomment next line and specify available locales
        # I18n.available_locales = [ :en, :nl, :pp ]

        # Uncomment next nine line if you want locale based on subdomain, like 'it.example.com, de.example.com'
        # def set_locale
        #   I18n.locale = extract_locale_from_subdomain || I18n.default_locale
        # end
        #
        # def extract_locale_from_subdomain
        #   locale = request.subdomains.first
        #   return nil if locale.nil?
        #   I18n.available_locales.include?(locale.to_sym) ? locale.to_s : nil
        # end
      end
    END_APPCONTROLLER

    say "- Creating Ability model so that the user with id = 1 can access all..."
    create_file "#{app_name}/app/models/ability.rb", <<-END_ABILITY.strip_heredoc_with_indent
      class Ability
        include CanCan::Ability

        def initialize(user)
          # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities

          user ||= user.new # guest user

          if user.id == 1 #quick hack
            can :access, :all
          else
            # put restrictions for other users here
          end
        end
      end
    END_ABILITY

    # create environments/production.rb if it's a dry run
    create_file "#{app_name}/config/environments/production.rb", "  # config.assets.precompile += %w( search.js )\nend\n" if dry_run?

    say "- Injecting precompile assets stuff in environments/production.rb..."
    insert_into_file "#{app_name}/config/environments/production.rb",
      "  config.assets.precompile += %w(inline_forms_application.js inline_forms_application.css devise.css)\n",
      :after => "  # config.assets.precompile += %w( search.js )\n"

    say "- Injecting devise mailer stuff in environments/production.rb..."
    insert_into_file "#{app_name}/config/environments/production.rb", <<-DEVISE_MAILER_STUFF.strip_heredoc_with_indent(2), :before => "end\n"

      # for devise
      config.action_mailer.default_url_options = { :protocol => 'https', :host => 'YOURHOSTNAME' }
      config.action_mailer.delivery_method = :smtp
      config.action_mailer.smtp_settings = {
        :address => 'YOURMAILSERVER',
        :enable_starttls_auto => true,
        :password => 'YOURPASSWORD',
        :user_name => 'YOURUSERNAME'
      }
      
    DEVISE_MAILER_STUFF

    say "- Setting autoload paths for ckeditor..."
    insert_into_file "#{app_name}/config/application.rb", '  config.autoload_paths += %W(#{config.root}/app/models/ckeditor)' + "\n", :after => "modules you want to be autoloadable.\n" unless dry_run?

    say "- Adding cancan authorization to ckeditor"
    gsub_file "#{app_name}/config/initializers/ckeditor.rb", "# config.authorize_with :cancan", "config.authorize_with :cancan" if File.exists?("#{app_name}/config/initializers/ckeditor.rb")

    say "- Capify..."
    run 'capify .'
    remove_file "#{app_name}/config/deploy.rb" # remove the file capify created!
    copy_file "lib/generators/templates/deploy.rb", "#{app_name}/config/deploy.rb"

    say "- Unicorn Config..."
    copy_file "lib/generators/templates/unicorn.rb", "#{app_name}/config/unicorn.rb"

    say "- Initializing git..."
    run 'git init'
    create_file "#{app_name}/.gitignore", "/tmp\n" if dry_run?
    insert_into_file "#{app_name}/.gitignore", <<-GITIGNORE.strip_heredoc_with_indent, :after => "/tmp\n"
      # netbeans
      nbproject
      # remotipart uploads
      public/uploads
    GITIGNORE

    run 'git add .'
    run 'git commit -a -m " * Initial"'

    if install_example?
      say "\nInstalling example application..."
      run 'bundle exec rails g inline_forms Picture name:string caption:string image:image_field description:text apartment:belongs_to _presentation:\'#{name}\''
      run 'bundle exec rails generate uploader Image'
      run 'bundle exec rails g inline_forms Apartment name:string title:string description:text pictures:has_many pictures:associated _enabled:yes _presentation:\'#{name}\''
      run 'bundle exec rake db:migrate'
      say "\nDone! Now point your browser to http://localhost:3000/apartments !", :yellow
      say "\nPress ctlr-C to quit...", :yellow
      run 'bundle exec rails s'
    else
      say "\nDone! Now make your tables with 'bundle exec rails g inline_forms ...", :yellow
      #say "- Don't forget: edit .rvmrc, config/{routes.rb, deploy.rb}, .git/config, delete public/index.html\n"
    end

  end
end