Module: Thoth

Includes:
Innate::Traited
Defined in:
lib/thoth.rb,
lib/thoth.rb,
lib/thoth.rb,
lib/thoth/cache.rb,
lib/thoth/config.rb,
lib/thoth/errors.rb,
lib/thoth/plugin.rb,
lib/thoth/version.rb,
lib/thoth/importer.rb,
lib/thoth/model/tag.rb,
lib/thoth/controller.rb,
lib/thoth/model/page.rb,
lib/thoth/model/post.rb,
lib/thoth/helper/wiki.rb,
lib/thoth/model/media.rb,
lib/thoth/helper/admin.rb,
lib/thoth/helper/error.rb,
lib/thoth/helper/cookie.rb,
lib/thoth/model/comment.rb,
lib/thoth/controller/tag.rb,
lib/thoth/helper/ysearch.rb,
lib/thoth/controller/main.rb,
lib/thoth/controller/page.rb,
lib/thoth/controller/post.rb,
lib/thoth/controller/admin.rb,
lib/thoth/controller/media.rb,
lib/thoth/controller/search.rb,
lib/thoth/helper/pagination.rb,
lib/thoth/helper/pagination.rb,
lib/thoth/middleware/minify.rb,
lib/thoth/plugin/thoth_tags.rb,
lib/thoth/controller/api/tag.rb,
lib/thoth/controller/archive.rb,
lib/thoth/controller/comment.rb,
lib/thoth/controller/api/page.rb,
lib/thoth/controller/api/post.rb,
lib/thoth/plugin/thoth_flickr.rb,
lib/thoth/model/tags_posts_map.rb,
lib/thoth/plugin/thoth_twitter.rb,
lib/thoth/plugin/thoth_pinboard.rb,
lib/thoth/controller/api/comment.rb,
lib/thoth/plugin/thoth_delicious.rb

Overview

– Copyright © 2009 Ryan Grove <[email protected]> All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
* Neither the name of this project nor the names of its contributors may be
  used to endorse or promote products derived from this software without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ++

Defined Under Namespace

Modules: Config, Helper, Plugin Classes: AdminController, ArchiveController, Cache, Comment, CommentApiController, CommentController, ConfigError, Controller, Error, Importer, MainController, Media, MediaController, Minify, Page, PageApiController, PageController, Pager, Post, PostApiController, PostController, SchemaError, SearchController, Tag, TagApiController, TagController, TagsPostsMap

Constant Summary collapse

HOME_DIR =
ENV['THOTH_HOME'] || File.expand_path('.')
LIB_DIR =
File.join(File.dirname(File.expand_path(__FILE__)), 'thoth')
PUBLIC_DIR =
File.join(LIB_DIR, 'public')
VIEW_DIR =
File.join(LIB_DIR, 'view')
FILESIZE_FORMAT =

Lifted from old Ramaze, which was also lifter by Rack::Directory Stolen from Ramaze

[
  ['%.1fT', 1 << 40],
  ['%.1fG', 1 << 30],
  ['%.1fM', 1 << 20],
  ['%.1fK', 1 << 10],
]
APP_NAME =
'Rethoth'
APP_VERSION =
'0.4.2'
APP_AUTHORS =
['John Pagonis' ,'Ryan Grove']
APP_EMAIL =
'[email protected]'
APP_URL =
'https://github.com/pagojo/rethoth'
'Copyright (c) 2009 - 2012 Ryan Grove <[email protected]>,  2017 John Pagonis <[email protected]>. All rights reserved.'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.dbObject (readonly)

Returns the value of attribute db.



155
156
157
# File 'lib/thoth.rb', line 155

def db
  @db
end

Class Method Details

.acquire(*globs) ⇒ Object

LIFTED from old Ramaze.acquire Require all .rb and .so files on the given globs, utilizes Dir::[].

Examples:

# Given following directory structure:
# src/foo.rb
# src/bar.so
# src/foo.yaml
# src/foobar/baz.rb
# src/foobar/README

# requires all files in 'src':
Ramaze.acquire 'src/*'

# requires all files in 'src' recursive:
Ramaze.acquire 'src/**/*'

# require 'src/foo.rb' and 'src/bar.so' and 'src/foobar/baz.rb'
Ramaze.acquire 'src/*', 'src/foobar/*'


81
82
83
84
85
86
87
88
# File 'lib/thoth.rb', line 81

def self.acquire(*globs)
 globs.flatten.each do |glob|
   Dir[glob].each do |file|
       require file if file =~ /\.(rb|so)$/
       puts "#{file} loaded"
     end
  end
end

.create(path) ⇒ Object

Creates a new Thoth home directory with a sample config file at the specified path.



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

def create(path)
  path = File.expand_path(path)
  
  puts "PATH #{path}"

  if File.exist?(path)
    raise "specified path already exists: #{path}"
  end

  FileUtils.mkdir_p(File.join(path, 'log'))
  FileUtils.mkdir(File.join(path, 'media'))
  FileUtils.mkdir(File.join(path, 'plugin'))
  FileUtils.mkdir(File.join(path, 'public'))
  FileUtils.mkdir(File.join(path, 'view'))
  FileUtils.mkdir(File.join(path, 'tmp'))

  FileUtils.cp(File.join(LIB_DIR, '..', 'proto', 'config.ru'), File.join(path, 'config.ru'))
  FileUtils.cp(File.join(LIB_DIR, '..', 'proto', 'thoth.conf.sample'), File.join(path, 'thoth.conf'))

  File.chmod(0750, File.join(path, 'log'))
  File.chmod(0750, File.join(path, 'media'))
  File.chmod(0750, File.join(path, 'plugin'))
  File.chmod(0755, File.join(path, 'public'))
  File.chmod(0750, File.join(path, 'view'))
  File.chmod(0750, File.join(path, 'tmp'))

  File.chmod(0640, File.join(path, 'config.ru'))
  File.chmod(0640, File.join(path, 'thoth.conf'))
end

.filesize_format(int) ⇒ Object



100
101
102
103
104
105
106
# File 'lib/thoth.rb', line 100

def self.filesize_format(int)
   FILESIZE_FORMAT.each do |format, size|
     return format % (int.to_f / size) if int >= size
   end

   "#{int}B"
end

.init_thothObject

Opens a connection to the Thoth database and loads helpers, controllers, models and plugins.



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

def init_thoth
  trait[:ip]   ||= Config.server['address']
  trait[:port] ||= Config.server['port']

  open_db

  # Ensure that the database schema is up to date.
  #
  # TODO: need to rethink how migration works since newer versions of Sequel
  # don't expose the migration versions.
  #
  # unless Sequel::Migrator.get_current_migration_version(@db) ==
  #     Sequel::Migrator.latest_migration_version(File.join(LIB_DIR, 'migrate'))
  # 
  #   if trait[:mode] == :production
  #     raise SchemaError, "Database schema is missing or out of date. " <<
  #         "Please run `thoth --migrate`."
  #   else
  #     raise SchemaError, "Database schema is missing or out of date. " <<
  #         "Please run `thoth --devel --migrate`."
  #   end
  # end

  # If caching is disabled, replace the default cache store with a no-op
  # API.
  if Config.server['enable_cache']
    # Cache templates once read to prevent unnecessary disk thrashing.
    Innate::View.options.read_cache = true

    if Config.server['memcache']['enabled']
      Ramaze::Cache::MemCache::OPTIONS[:servers] = Config.server['memcache']['servers']
      Ramaze::Cache.options.default = Ramaze::Cache::MemCache
    end
  else
    require 'thoth/cache'
    Ramaze::Cache.options.default = Thoth::Cache::Noop
  end

  # Create a cache for plugins to use.
  Ramaze::Cache.add(:plugin)

  # Tell Innate where to find Thoth's helpers.
  Innate::HelpersHelper.options.paths << LIB_DIR
  Innate::HelpersHelper.options.namespaces << Thoth::Helper

  # Load Thoth controllers.
  require File.join(LIB_DIR, 'controller')

  # Load Thoth models.
  require File.join(LIB_DIR, 'helper/wiki')
  Thoth.acquire(File.join(LIB_DIR, 'model', '*'))

  # Load startup plugins.
  Config.plugins.each {|plugin| Plugin.load(plugin)}

  Ramaze::Log.info "Thoth home: #{HOME_DIR}"
  Ramaze::Log.info "Thoth lib : #{LIB_DIR}"
  Ramaze::Log.info "Running in #{trait[:mode] == :production ? 'live' : 'dev'} mode"

  Ramaze.options.setup << self
end

.open_dbObject

Opens a Sequel database connection to the Thoth database.



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/thoth.rb', line 254

def open_db
  if Config.db =~ /^sqlite:\/{3}(.+)$/
    dir = File.dirname($1)
    FileUtils.mkdir_p(dir) unless File.directory?(dir)
  end

  Sequel.datetime_class = Time

  @db = Sequel.connect(Config.db, :encoding => 'utf8')
  @db.test_connection

  if trait[:sql_log]
    require 'logger'
    @db.logger = Logger.new(trait[:sql_log])
  end
  
  @db.extension(:pagination)

rescue => e
  Ramaze::Log.error("Unable to connect to database: #{e}")
  exit(1)
end

.restartObject

Restarts the running Thoth daemon (if any).



278
279
280
281
282
# File 'lib/thoth.rb', line 278

def restart
  stop
  sleep(1)
  start
end

.runObject

Runs Thoth.



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/thoth.rb', line 285

def run
  init_thoth

  begin
    Ramaze.start(
      :adapter => trait[:adapter],
      :host    => trait[:ip],
      :port    => trait[:port],
      :root    => LIB_DIR
    )
  rescue LoadError => ex
    Ramaze::Log.error("Unable to start Ramaze due to LoadError: #{ex}")
    exit(1)
  end
end

.setupObject

Initializes Ramaze.



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

def setup
  Ramaze.options.merge!(
    :mode  => trait[:mode] == :production ? :live : :dev,
    :roots => [HOME_DIR, LIB_DIR]
  )
  
  case trait[:mode]
  when :devel
    Ramaze.middleware :dev do 
      use Rack::Lint
      use Rack::CommonLogger, Ramaze::Log
      use Rack::ShowExceptions
      use Rack::ShowStatus
      use Rack::RouteExceptions
      use Rack::ConditionalGet
      use Rack::ETag
      use Rack::Head
      use Ramaze::Reloader
      use Thoth::Minify if Config.server['enable_minify']
      run Ramaze::AppMap
    end

  when :production
    Ramaze.middleware :live do 
      use Rack::CommonLogger, Ramaze::Log
      use Rack::RouteExceptions
      use Rack::ShowStatus
      use Rack::ConditionalGet
      use Rack::ETag
      use Rack::Head
      use Thoth::Minify if Config.server['enable_minify']
      run Ramaze::AppMap
    end

    # Ensure that exceptions result in an HTTP 500 response.
    Rack::RouteExceptions.route(Exception, '/error_500')

    # Log all errors to the error log file if one is configured.
    if Config.server['error_log'].empty?
      Ramaze::Log.loggers = []
    else
      log_dir = File.dirname(Config.server['error_log'])

      unless File.directory?(log_dir)
        FileUtils.mkdir_p(log_dir)
        File.chmod(0750, log_dir)
      end

      Ramaze::Log.loggers = [Logger.new(Config.server['error_log'])]
      Ramaze::Log.level = Logger::Severity::ERROR
    end
  end
end

.startObject

Starts Thoth as a daemon.



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

def start
  if File.file?(trait[:pidfile])
    pid = File.read(trait[:pidfile], 20).strip
    abort("thoth already running? (pid=#{pid})")
  end

  puts "Starting thoth."

  fork do
    Process.setsid
    exit if fork

    File.open(trait[:pidfile], 'w') {|file| file << Process.pid}
    at_exit {FileUtils.rm(trait[:pidfile]) if File.exist?(trait[:pidfile])}

    Dir.chdir(HOME_DIR)
    File.umask(0000)

    STDIN.reopen('/dev/null')
    STDOUT.reopen('/dev/null', 'a')
    STDERR.reopen(STDOUT)

    run 
  end
end

.stopObject

Stops the running Thoth daemon (if any).



384
385
386
387
388
389
390
391
392
393
394
# File 'lib/thoth.rb', line 384

def stop
  unless File.file?(trait[:pidfile])
    abort("thoth not running? (check #{trait[:pidfile]}).")
  end

  puts "Stopping thoth."

  pid = File.read(trait[:pidfile], 20).strip
  FileUtils.rm(trait[:pidfile]) if File.exist?(trait[:pidfile])
  pid && Process.kill('TERM', pid.to_i)
end