Module: CortexReaver

Defined in:
lib/cortex_reaver/cache.rb,
lib/cortex_reaver.rb,
lib/cortex_reaver/config.rb,
lib/cortex_reaver/plugin.rb,
lib/cortex_reaver/version.rb,
lib/cortex_reaver/model/tag.rb,
lib/cortex_reaver/model/page.rb,
lib/cortex_reaver/model/user.rb,
lib/cortex_reaver/model/comment.rb,
lib/cortex_reaver/model/journal.rb,
lib/cortex_reaver/controller/tag.rb,
lib/cortex_reaver/controller/main.rb,
lib/cortex_reaver/controller/page.rb,
lib/cortex_reaver/controller/user.rb,
lib/cortex_reaver/plugins/twitter.rb,
lib/cortex_reaver/controller/admin.rb,
lib/cortex_reaver/model/photograph.rb,
lib/cortex_reaver/support/renderer.rb,
lib/cortex_reaver/controller/config.rb,
lib/cortex_reaver/controller/comment.rb,
lib/cortex_reaver/controller/journal.rb,
lib/cortex_reaver/migrations/006_tags.rb,
lib/cortex_reaver/migrations/001_users.rb,
lib/cortex_reaver/migrations/002_pages.rb,
lib/cortex_reaver/migrations/009_mysql.rb,
lib/cortex_reaver/migrations/013_draft.rb,
lib/cortex_reaver/controller/controller.rb,
lib/cortex_reaver/controller/controller.rb,
lib/cortex_reaver/controller/photograph.rb,
lib/cortex_reaver/migrations/008_config.rb,
lib/cortex_reaver/migrations/003_journals.rb,
lib/cortex_reaver/migrations/005_projects.rb,
lib/cortex_reaver/migrations/007_comments.rb,
lib/cortex_reaver/controller/documentation.rb,
lib/cortex_reaver/migrations/011_user_roles.rb,
lib/cortex_reaver/migrations/004_photographs.rb,
lib/cortex_reaver/migrations/010_pageparents.rb,
lib/cortex_reaver/migrations/015_page_comments.rb,
lib/cortex_reaver/migrations/016_drop_comment_titles.rb,
lib/cortex_reaver/migrations/012_created_by_edited_by.rb,
lib/cortex_reaver/migrations/014_convert_projects_to_pages.rb

Overview

Require controllers

Defined Under Namespace

Modules: Model, Plugins Classes: AdminController, Cache, Comment, CommentController, CommentSchema, CommentsEnabledOnPagesSchema, Config, ConfigController, ConfigSchema, Controller, CreatedbyeditedbySchema, DocumentationController, DraftSchema, DropCommentTitlesSchema, Journal, JournalController, JournalSchema, MainController, MySQLSchema, Page, PageController, PageSchema, PageparentsSchema, Photograph, PhotographController, PhotographSchema, ProjectSchema, ProjectsToPagesSchema, Tag, TagController, TagSchema, User, UserController, UserSchema, UserrolesSchema

Constant Summary collapse

ROOT =

Paths

File.expand_path(File.join(__DIR__, '..'))
LIB_DIR =
File.expand_path(File.join(ROOT, 'lib', 'cortex_reaver'))
HOME_DIR =
File.expand_path(Dir.pwd)
APP_NAME =
'Cortex Reaver'
APP_VERSION =
'0.3.1'
APP_AUTHOR =
'Kyle Kingsbury'
APP_EMAIL =
'[email protected]'
APP_URL =
'http://aphyr.com'
'Copyright (c) 2009--2011 Kyle Kingsbury <[email protected]>. All rights reserved.'
Attachment =
Sequel::Plugins::Attachments::Attachment

Class Method Summary collapse

Class Method Details

.collect_files(stock_dir, custom_dir, pattern = /^[^\.].+/, opts = {}) ⇒ Object

Reads files from stock_dir and custom_dir matching pattern, and appends their contents. Returns a string.



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
# File 'lib/cortex_reaver.rb', line 43

def self.collect_files(stock_dir, custom_dir, pattern = /^[^\.].+/, opts = {})
  str = ""
  # Get target files
  files = Dir.entries(stock_dir) | Dir.entries(custom_dir)

  # Reorder files if necessary.
  first = (opts[:first] || []) & files
  last = (opts[:last] || []) & files
  files = first + (files - first - last) + last

  # Read files
  files.each do |file|
    next unless file =~ pattern
    custom_file = File.join(custom_dir, file)
    stock_file = File.join(stock_dir, file)
    if File.exists? custom_file
      str << File.read(custom_file)
    else
      str << File.read(stock_file)
    end
    str << "\n"
  end

  str
end

.compile_cssObject

Compiles CSS files and creates minified version.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cortex_reaver.rb', line 70

def self.compile_css
  Ramaze::Log.info "Compiling CSS"
  stock_dir = File.join(LIB_DIR, 'public', 'css')
  custom_dir = File.join(config.public_root, 'css')

  # Get CSS files
  FileUtils.mkdir_p(custom_dir)
  css = collect_files(
    stock_dir, 
    custom_dir, 
    /^((?!style).)*\.css$/, 
    :first => config.css[:first],
    :last => config.css[:last]
  )

  # Write minified CSS
  File.open(File.join(custom_dir, 'style.css'), 'w') do |file|
    file.write CSSMin.minify(css)
  end
end

.compile_jsObject

Compiles JS files and creates minified version.



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/cortex_reaver.rb', line 92

def self.compile_js
  Ramaze::Log.info "Compiling JS"
  stock_dir = File.join(LIB_DIR, 'public', 'js')
  custom_dir = File.join(config.public_root, 'js')

  # Get JS files
  FileUtils.mkdir_p(custom_dir)
  js = collect_files(
    stock_dir, 
    custom_dir, 
    /^((?!site).)*\.js$/, 
    :first => config.js[:first],
    :last => config.js[:last]
  )

  # Write minified JS
  File.open(File.join(custom_dir, 'site.js'), 'w') do |file|
    file.write js #JSMin.minify(js)
  end
end

.compile_resourcesObject



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
# File 'lib/cortex_reaver.rb', line 113

def self.compile_resources
  # Prepare CSS/JS
  self.compile_css
  self.compile_js

  if config.mode == :development
    # Recompile CSS/JS on changes.
    @asset_compiler = Thread.new do
      # Get files to watch
      files = Dir.glob(File.join(LIB_DIR, 'public', 'css', '*.css'))
      files |= Dir.glob(File.join(config.public_root, 'css', '*.css'))
      files |= Dir.glob(File.join(LIB_DIR, 'public', 'js', '*.js'))
      files |= Dir.glob(File.join(config.public_root, 'js', '*.js'))
      files -= [
        File.join(config.public_root, 'css', 'style.css'),
        File.join(config.public_root, 'js', 'site.js')
      ]
      last = {}

      # Get initial modification times.
      files.each do |f|
        last[f] = File.stat(f).mtime
      end

      loop do
        # Check files
        rebuild = false
        files.each do |f|
          mtime = File.stat(f).mtime
          if last[f] < mtime
            last[f] = mtime
            rebuild = true
          end
        end

        if rebuild
          # Recompile
          self.compile_css
          self.compile_js
        end
      
        sleep 2
      end
    end
  end
end

.configObject

Returns the site configuration



161
162
163
# File 'lib/cortex_reaver.rb', line 161

def self.config
  @config
end

.config_fileObject



165
166
167
# File 'lib/cortex_reaver.rb', line 165

def self.config_file
  @config_file || File.join(Dir.pwd, 'cortex_reaver.yaml')
end

.config_file=(file) ⇒ Object



169
170
171
# File 'lib/cortex_reaver.rb', line 169

def self.config_file=(file)
  @config_file = file
end

.content_rangeObject

The total span of items in the CR DB, for copyright notices and such.



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/cortex_reaver.rb', line 174

def self.content_range
  return @content_range if @content_range

  @content_range = [Journal, Page, Photograph].inject(nil) do |total, ds|
    begin
      if total
        total | ds.range(:created_on)
      else
        ds.range(:created_on)
      end
    rescue
      # Some range was invalid
      total
    end
  end
  if @content_range.first.kind_of? String 
    @content_range = DateTime.parse(@content_range.begin) .. DateTime.parse(@content_range.end)
  end

  # If there's no content, default to today!
  @content_range ||= Time.now .. Time.now
end

.create_directoriesObject

Creates the app directories if they don’t exist.



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
# File 'lib/cortex_reaver.rb', line 198

def self.create_directories
  # view
  if config.view_root
    if not File.directory? config.view_root
      # Try to create a view directory
      begin
        FileUtils.mkdir_p config.view_root
      rescue => e
        Ramaze::Log.warn "Unable to create a view directory at #{config.view_root}: #{e}."
      end
    end
  end

  # public
  if config.public_root and not File.directory? config.public_root
    # Try to create a public directory
    begin
      FileUtils.mkdir_p config.public_root
    rescue => e
      Ramaze::Log.warn "Unable to create a public directory at #{config.public_root}: #{e}."
    end
  end

  # log
  if config[:log_root] and not File.directory? config[:log_root]
    # Try to create a log directory
    begin
      FileUtils.mkdir_p config[:log_root]
      File.chmod 0750, config[:log_root]
    rescue => e
      Ramaze::Log.warn "Unable to create a log directory at #{config[:log_root]}: #{e}. File logging disabled."
      # Disable logging
      config[:log_root] = nil
    end
  end
end

.dbObject



235
236
237
# File 'lib/cortex_reaver.rb', line 235

def self.db
  @db
end

.initObject

Prepare Ramaze, create directories, etc.



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
# File 'lib/cortex_reaver.rb', line 240

def self.init
  # App
  Ramaze.options.app.name = :cortex_reaver
  
  # Helper load path
  Ramaze.options.helpers_helper.paths.unshift LIB_DIR
 
  # Load controllers 
  require File.join(LIB_DIR, 'controller', 'controller')

  # Server options
  Ramaze.options.adapter.handler = config[:adapter]
  Ramaze.options.adapter.host = config[:host]
  Ramaze.options.adapter.port = config[:port]

  # App mode
  case config[:mode]
  when :production
    Ramaze.options.mode = :live
  when :development
    Ramaze.options.mode = :dev
    Ramaze.middleware! :dev do |m|
      # Rack::Lint is broken on 1.9.1, it looks like.
#       m.use Rack::Lint
      m.use Rack::RouteExceptions
      m.use Rack::ShowExceptions
      m.use Rack::CommonLogger, Ramaze::Log
      m.use Ramaze::Reloader
      m.use Rack::ShowStatus
      m.use Rack::Head
      m.use Rack::ETag
      m.use Rack::ConditionalGet
      m.use Rack::ContentLength
      m.run Ramaze::AppMap
    end
  else
    raise ArgumentError.new("unknown Cortex Reaver mode #{config.mode.inspect}. Expected one of [:production, :development].")
  end
  
  create_directories
  setup_logging
  setup_cache
  compile_resources
  load_plugins
end

.loadObject

Load libraries



287
288
289
290
291
292
293
294
295
296
# File 'lib/cortex_reaver.rb', line 287

def self.load
  # Load controllers and models
  require File.join(LIB_DIR, 'version')
  require File.join(LIB_DIR, 'config')
  require File.join(LIB_DIR, 'plugin')
  Ramaze::acquire File.join(LIB_DIR, 'snippets', '**', '*')
  Ramaze::acquire File.join(LIB_DIR, 'support', '*')
  require File.join(LIB_DIR, 'cache')
  require File.join(LIB_DIR, 'model', 'model')
end

.load_pluginsObject

Load plugins



299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/cortex_reaver.rb', line 299

def self.load_plugins
  # Create plugin cache
  Ramaze::Cache.add :plugin

  # Load plugins
  config.plugins.enabled.each do |plugin|
    Ramaze::Log.info "Loading plugin #{plugin}"
    begin
      require File.join(config.plugin_root, plugin)
    rescue LoadError => e
      require File.join(LIB_DIR, 'plugins', plugin)
    end
  end
end

.reloadObject

Tells the running CortexReaver to reload.



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
# File 'lib/cortex_reaver.rb', line 315

def self.reload
  reload_config

  unless config.pidfile
    abort "No pidfile to reload."
  end

  unless File.file? config.pidfile
    abort "Cortex Reaver not running? (check #{config.pidfile})"
  end

  # Get PID
  pid = File.read(config.pidfile, 20).strip
  unless (pid = pid.to_i) != 0
    abort "Invalid process ID in pidfile (#{pid})."
  end

  puts "Reloading Cortex Reaver #{pid}..."
  
  begin
    # Try to shut down Ramaze nicely.
    Process.kill('USR1', pid)
    puts "Done."
  rescue Errno::ESRCH
    # The process doesn't exist.
    puts "No Cortex Reaver with pid #{pid}."
  rescue => e
    # That failed, too.
    puts "Unable to reload Cortex Reaver: #{e}."
  end
end

.reload_appObject

Reloads the app without restarting.



348
349
350
351
352
353
354
# File 'lib/cortex_reaver.rb', line 348

def self.reload_app
  self.reload_config
  self.load
  self.init
  self.compile_css
  self.compile_js
end

.reload_configObject

Reloads the site configuration



357
358
359
360
361
362
363
# File 'lib/cortex_reaver.rb', line 357

def self.reload_config
  begin
    @config = CortexReaver::Config.load(File.read(config_file))
  rescue Errno::ENOENT
    @config = CortexReaver::Config.new
  end
end

.restartObject

Restart Cortex Reaver



366
367
368
369
370
371
372
373
374
# File 'lib/cortex_reaver.rb', line 366

def self.restart
  begin
    stop
    # Wait for Cortex Reaver to finish, and for the port to become available.
    sleep 2
  ensure
    start
  end
end

.runObject

Once environment is prepared, run Ramaze



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/cortex_reaver.rb', line 377

def self.run
  # Shutdown callback
  at_exit do
    # Remove pidfile
    FileUtils.rm(config.pidfile) if File.exist? config.pidfile
  end

  Ramaze::Log.info "Cortex Reaver #{Process.pid} stalking victims."

  # Run Ramaze
  roots = [LIB_DIR]
  roots.unshift config.root if config.root
  Ramaze.start :root => roots

  puts "Cortex Reaver finished."
end

.setupObject

Load Cortex Reaver environment; do everything except start Ramaze



395
396
397
398
399
400
401
402
403
404
# File 'lib/cortex_reaver.rb', line 395

def self.setup
  # Connect to DB
  setup_db

  # Load library
  self.load

  # Prepare Ramaze, check directories, etc.
  init
end

.setup_cacheObject



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
# File 'lib/cortex_reaver.rb', line 431

def self.setup_cache
  # Set up cache
  case config.cache
  when :memcache
    Ramaze::Cache::MemCache::OPTIONS[:servers] = config.memcache.servers
    Ramaze::Cache.options.default = Ramaze::Cache::MemCache

    # Cache templates
    Innate::View.options.read_cache = true
  else
    # Cache stub
    # Hmm, this breaks session management.
#      Ramaze::Log.warn "Caching disabled."
#      Ramaze::Cache.options.default = CortexReaver::Cache::Noop
  end

  # Test caching
  Ramaze::Cache.add(:cortex_reaver)

  begin
    Ramaze::Cache.cortex_reaver.store :test, true
  rescue => e
    Ramaze::Log.warn "Cache is broken: #{e}"
    Ramaze::Log.warn "Falling back to memory cache."
    Ramaze::Cache.options.default = Ramaze::Cache::Memory
  end
end

.setup_db(check_schema = true) ⇒ Object

Connect to DB. If check_schema is false, doesn’t check to see that the schema version is up to date.



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/cortex_reaver.rb', line 408

def self.setup_db(check_schema = true)
  unless config
    raise RuntimeError.new("no configuration available!")
  end

  # Connect
  begin
    @db = Sequel.connect(config.database.str)
  rescue => e
    Ramaze::Log.error("Unable to connect to database: #{e}.")
    abort
  end

  # Check schema
  #TODO: Disabled due to migrator API changes.
#    if check_schema and
#       Sequel::Migrator.get_current_migration_version(@db) !=
#       Sequel::Migrator.latest_migration_version(File.join(LIB_DIR, 'migrations'))
#
#      raise RuntimeError.new("database schema missing or out of date. Please run `cortex_reaver --migrate`.")
#    end
end

.setup_loggingObject



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
# File 'lib/cortex_reaver.rb', line 459

def self.setup_logging
  # Clear loggers
  Ramaze::Log.loggers.clear

  unless config.daemon
    # Log to console
    Ramaze::Log.loggers << Logger.new(STDOUT)
  end

  if config.log_root
    # Log to files
    case config.mode
    when :production
      logfile = 'production.log'
      level = Logger::Severity::INFO
    when :development
      logfile = 'development.log'
      level = Logger::Severity::DEBUG

      # Also use SQL log
      db.logger = Logger.new(
        File.join(config.log_root, 'sql.log')
      )
    end

    # Create file logger      
    Ramaze::Log.loggers << Logger.new(
      File.join(config.log_root, logfile)
    )
    Ramaze::Log.level = level
  end
end

.shutdown_dbObject

Disconnect from DB



493
494
495
496
# File 'lib/cortex_reaver.rb', line 493

def self.shutdown_db
  @db.disconnect
  @db = nil
end

.startObject



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/cortex_reaver.rb', line 498

def self.start
  reload_config

  # Check PID
  if File.file? config.pidfile
    pid = File.read(config.pidfile, 20).strip
    abort "Cortex Reaver already running? (#{pid})"
  end

  puts "Activating Cortex Reaver."
  setup

  if config.daemon
    fork do
      # Drop console, create new session
      Process.setsid
      exit if fork

      # Write pidfile
      File.open(config.pidfile, 'w') do |file|
        file << Process.pid
      end

      # Move to homedir; drop creation mask
      Dir.chdir HOME_DIR
      File.umask 0000

      # Drop stream handles
      STDIN.reopen('/dev/null')
      STDOUT.reopen('/dev/null', 'a')
      STDERR.reopen(STDOUT)

      # Go!
      run
    end
  else
    # Write pidfile
    File.open(config.pidfile, 'w') do |file|
      file << Process.pid
    end
    
    # Run in foreground.
    run
  end
end

.stopObject



544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/cortex_reaver.rb', line 544

def self.stop
  reload_config

  unless config.pidfile
    abort "No pidfile to stop."
  end

  unless File.file? config.pidfile
    abort "Cortex Reaver not running? (check #{config.pidfile})"
  end

  # Get PID
  pid = File.read(config.pidfile, 20).strip
  unless (pid = pid.to_i) != 0
    abort "Invalid process ID in pidfile (#{pid})."
  end

  puts "Shutting down Cortex Reaver #{pid}..."
  
  # Attempt to end Ramaze nicely.
  begin
    # Try to shut down Ramaze nicely.
    Process.kill('INT', pid)
    puts "Shut down."
    killed = true
  rescue Errno::ESRCH
    # The process doesn't exist.
    puts "No Cortex Reaver with pid #{pid}."
    killed = true
  rescue => e
    begin
      # Try to end the process forcibly.
      puts "Cortex Reaver #{pid} has gone rogue (#{e}); forcibly terminating..."
      Process.kill('KILL', pid)
      puts "Killed."
      killed = true
    rescue => e2
      # That failed, too.
      puts "Unable to terminate Cortex Reaver: #{e2}."
      killed = false
    end
  end

  # Remove pidfile if killed.
  if killed
    begin
      FileUtils.rm(config.pidfile)
    rescue Errno::ENOENT
      # Pidfile gone
    rescue => e
      puts "Unable to remove pidfile #{config.pidfile}: #{e}."
    end
  end
end