Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
MOZGIII committed Apr 29, 2012
0 parents commit 06b640a
Show file tree
Hide file tree
Showing 39 changed files with 1,368 additions and 0 deletions.
5 changes: 5 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
== aero

Все права на данный проект принадлежат ГОУ МГИУ. Использование его
в коммерческих или других целях является преступлением, преследуемым
законодательством РФ и зарубежных стран.
39 changes: 39 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
== aero

Для установки проделайте следующие шаги:

0. Распаковываем проект
0.1. scp архив_с_проектом мой_новый_логин_на_удаленной_машине@asrv9-ctx-7:/куда_положить_архив
0.2. если спросило (yes/no) печатаем yes и нажимаем Enter
0.3. ssh asrv9-ctx-7 -l мой_новый_логин_на_этой_машине
0.4. см. пункт 0.2.
0.5. cd куда_положить_архив
0.6. tar xzvf архив_с_проектом
(теперь путь_до_папки_с_проектом = /куда_положить_архив/aero)
1. Инициализируем свою разработческую базу данных при помощи initdb
1.1. export LC_ALL=ru_RU.UTF-8
1.2. initdb -D папка_где_я_хочу_хранить_базу
1.3. pg_ctl -D папка_где_я_хочу_хранить_базу -o "-i -p мой_уникальный_порт" start
1.4. создаем в репозитории пользователя worker
1.4.1. psql -p мой_уникальный_порт template1
1.4.2. выполняем в БД команду:
CREATE USER worker WITH PASSWORD 'worker' CREATEDB;
1.4.3. выходим, нажав Ctrl+d
2. Создаем ссылки на свое приложение в папке /var/www
2.1. cd /var/www/cgi-bin/мой_новый_логин_на_удаленной_машине
2.2. ln -sf путь_до_папки_с_проектом/lib aero
2.3. cd /var/www/html/мой_новый_логин_на_удаленной_машине
2.4. ln -sf путь_до_папки_с_проектом/lib/stylesheets
2.5. меняем в файле проекта путь_до_папки_с_проектом/lib/templates/layout/header.rb
адрес /stylesheets/aero.css на /мой_новый_логин_на_удаленной_машине/stylesheets/aero.css
3. Инициализируем БД
3.1. Меняем в файле путь_до_папки_с_проектом/lib/db_core/db_driver.rb порт 5432 на мой_уникальный_порт
3.2. cd путь_до_папки_с_проектом
3.3. rake test
4. Открываем в браузере
4.1. Открываем свою папку и папку с проектом на просмотр для всех:
4.1.1. chmod 755 ~
4.1.2. chmod 755 путь_до_папки_с_проектом -R
4.2. Запускаем браузер
4.3. Открываем адрес: asrv9-ctx-7.msiu.ru/cgi-bin/мой_новый_логин_на_удаленной_машине/aero/aero.rb
5. Если что-то не так, то возвращаемся к пункту 0 и внимательно ищем ошибку!
45 changes: 45 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#
# To change this template, choose Tools | Templates
# and open the template in the editor.


require 'rubygems'
require 'rake'
require 'rake/clean'
require 'rake/gempackagetask'
require 'rake/rdoctask'
require 'rake/testtask'

spec = Gem::Specification.new do |s|
s.name = 'aero'
s.version = '0.0.1'
s.has_rdoc = true
s.extra_rdoc_files = ['README', 'LICENSE']
s.summary = 'Your summary here'
s.description = s.summary
s.author = ''
s.email = ''
# s.executables = ['your_executable_here']
s.files = %w(LICENSE README Rakefile) + Dir.glob("{bin,lib,spec}/**/*")
s.require_path = "lib"
s.bindir = "bin"
end

Rake::GemPackageTask.new(spec) do |p|
p.gem_spec = spec
p.need_tar = true
p.need_zip = true
end

Rake::RDocTask.new do |rdoc|
files =['README', 'LICENSE', 'lib/**/*.rb']
rdoc.rdoc_files.add(files)
rdoc.main = "README" # page to start on
rdoc.title = "aero Docs"
rdoc.rdoc_dir = 'doc/rdoc' # rdoc output folder
rdoc.options << '--line-numbers'
end

Rake::TestTask.new do |t|
t.test_files = FileList['test/**/*.rb']
end
46 changes: 46 additions & 0 deletions lib/aero.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/local/bin/ruby

require 'cgi'
require 'controllers/controller'
require 'convertors'

DEFAULT_CONTROLLER = 'Flights'
DEFAULT_ACTION = 'departure_list'

def valid_controllers()
Dir[File.join(File.dirname(__FILE__), 'controllers', "*.rb")].map do
|f| Convertors::controller_file_to_class_name(f)
end
end

def render()
cgi = CGI.new('html4')
begin
unless cgi.params.include?('controller') or
valid_controllers.include?(cgi.params['controller'][0])
cgi.params['controller'] = [DEFAULT_CONTROLLER]
cgi.params['action'] = [DEFAULT_ACTION]
end
c = eval(cgi.params['controller'][0] + 'Controller').new(cgi)
cgi.out({
"type" => "text/html; charset=utf-8",
"language" => "ru"
}){ c.response() }
rescue Exception => e
cgi.out({
"type" => "text/html; charset=utf-8",
"language" => "ru"
}){ display_errors(e) }
end
end

def display_errors(e)
"
<html>
<head><title>Error!</title></head>
<body>#{e.message}<br>#{e.backtrace.join('<br>')}</body>
</html>
"
end

render()
25 changes: 25 additions & 0 deletions lib/controllers/auth_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class AuthController < Controller
def is_authorized_action?()
return false
end

def login()
if @cgi.params['action'][0] == 'login' and
@cgi.params['controller'][0] == 'Auth'
@reverse_action = DEFAULT_ACTION
@reverse_controller = DEFAULT_CONTROLLER
else
@reverse_action = @cgi.params['action'][0]
@reverse_controller = @cgi.params['controller'][0]
end
render_template(@action)
end

def logout()
@session.delete()
@session = nil
@reverse_action = DEFAULT_ACTION
@reverse_controller = DEFAULT_CONTROLLER
render_template(@action)
end
end
197 changes: 197 additions & 0 deletions lib/controllers/controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
require 'cgi'
require 'cgi/session'
require 'cgi/session/pstore'
require 'convertors'
require 'db_core/db_driver'
require 'rubygems'
require 'controllers/helper'

# Подключение всех db_core/models/*.rb
Dir[File.join(File.dirname(__FILE__), '..', 'db_core', 'models', "*.rb")].each do |f|
require(f)
end

class Controller
include Helper

DEFAULT_CONTROLLER = :Flights
DEFAULT_ACTION = :list

# Список всех контроллеров
def Controller.all_controllers()
Dir[File.join(File.dirname(__FILE__), '', "*.rb")].select do |f|
File.basename(f) != 'controller.rb'
end.map{ |f| Convertors.controller_file_to_class_name(f) }
end

# Методы, выполняющиеся до запуска основного действия
def before_filters
[:session, :set_action, :auth, :login_link, :menu]
end

# Методы, выполняющиеся после генерации осноного действия
def after_filters
[:save_session]
end

# Создание и/или подключение к сессии
def session()
@cgi = CGI.new('html4') if @cgi.nil?
@session = CGI::Session.new(@cgi,
'database_manager' => CGI::Session::PStore,
'session_key' => '_aero_sess_id',
'session_expires' => Time.now + 5 * 60,
'prefix' => 'pstore_aero_sid_') if @session.nil?
end

# Закрытие сессии
def save_session()
@session.close() unless @session.nil?
end

# Проверка прав доступа и, если нужно, перенаправление на ввод пароля
def auth()
if !@session['user'].nil? and @session['user'] != ''
@user = @session['user']
elsif @cgi.params.has_key?('user') and @cgi.params['user'][0] != '' and
@cgi.params.has_key?('password') and @cgi.params['password'][0] != ''
if User.check_user(@db, @cgi.params['user'][0], @cgi.params['password'][0])
@user = @cgi.params['user'][0]
@session['user'] = @user
else
@action = :login
@controller = :Auth
end
elsif !self.is_authorized_action?
@user = nil
else
@action = :login
@controller = :Auth
end
end

# Формирование ссылки в левом верхнем углу Вход/Выход
def login_link()
if @controller == :Auth
@login_link_html = '&nbsp;'
elsif !@user.nil?
@login_link_html = render_layout('logout_link')
else
@login_link_html = render_layout('login_link')
end
end

# Формирование меню
def menu()
@menu = Controller.all_controllers.map do |c|
eval(c + 'Controller').actions(@user).map do |a|
"<li><a href = 'aero.rb?controller=#{c.to_s}&action=#{a[0]}'>#{a[1]}</a></li>"
end.join("\n")
end.join("\n")
@menu = '<ul>' + @menu + '</ul>' unless @menu == ''
end

# Метод, отвечающий требует ли данный запрос доступа по паролю или нет
def is_authorized_action?()
return true
end

# Установка значение controller/action
def set_action()
params = @cgi.params
@action = params['action'][0].to_sym if @action.nil?
@controller = (params.has_key?('controller') ?
params['controller'][0].to_sym :
self.class.to_sym) if @controller.nil?
end

# Проверяет где искать метод (в текущем контроллере или нет)
def my_action?()
return @controller.to_s + 'Controller' == self.class.to_s
end

# Формирование html документа
def response()
render_layout('header', :rb) +
@html +
render_layout('footer', :rb)
end

# Формирование только содержимого тела html документа
def response_withot_layout()
@html
end

# Конструктор
def initialize(cgi = nil, session = nil, action = nil, controller = nil)
@action = action
@controller = controller
@db = DbDriver.instance()
@cgi = cgi unless cgi.nil?
@session = session unless session.nil?

before_filters().each{ |f| self.send(f.to_s) }

if my_action?()
@html = self.send(@action.to_s)
else
c = eval(@controller.to_s + 'Controller').new(@cgi, @session, @action,
@controller)
@html = c.response_withot_layout()
end

after_filters().each{ |f| self.send(f.to_s) }
DbDriver.close()
end

# Загружает html-код из файла в строку
def render_template(name, mode = :rb)
if mode == :rb
f = File.new("templates/#{Convertors.class_name_to_controller_dir(@controller)}/#{name}.rb")
html = eval(f.read)
f.close
return html
else
f = File.new("templates/#{@controller}/#{name}")
html = f.read
f.close
return html
end
end

# Загружает html-код из файла, лежащего в папке layout, в строку
def render_layout(name, mode = :html)
if mode == :rb
f = File.new("templates/layout/#{name}.rb")
html = eval(f.read)
f.close
return html
else
f = File.new("templates/layout/#{name}.html")
html = f.read
f.close
return html
end
end

# Возвращает списки элементов меню
def Controller.actions(user)
[]
end

# Выбирает из параметров только параметры с именем вида: prefix[имя]
def filter_for_params(prefix = 'item')
keys = @cgi.params.keys.select{ |k| k =~ /^#{prefix}/ }.map do
|k| k.gsub(/^#{prefix}\[(.*)\]$/, '\1')
end
params = {}
keys.each{ |k| params[k] = @cgi.params["#{prefix}[#{k}]"] }
return params
end
end

# Подключение всех *_controller.rb
Dir[File.join(File.dirname(__FILE__), '', "*.rb")].each do |f|
require f if File.basename(f) != 'controller.rb'
end

Loading

0 comments on commit 06b640a

Please sign in to comment.