Хорошая мотивация для перехода на rails, а для меня очередное подтверждение что я иду верной дорогой
кстати балбеков олег из тамбовской области
class Clientsale < ActiveRecord::Base
attr_accessible :comment, :company_name, :dolznost, :email, :fio, :phone, :project_id, :url_name, :user_id
#validates :email, email_format: { message: "Ошибка при вводе email", allow_nil: true, allow_empty: true }
validates_each :email, :phone do |record, attr, value|
record.errors.add(attr, 'Хотя бы один контакт должен быть указан') if $test_clientsale_00163563213_find_me_in_def_contact_test.empty?
end
validates_each :company_name, :url_name do |record, attr, value|
record.errors.add(attr, 'Хотя бы один параметр (Адрес сайта или Название компании) ') if $test_url_and_name_company_56456456__find_me_in_def_contact_test.empty?
end
before_validation :contact_test
before_save :set_user_project
private
def contact_test
$test_clientsale_00163563213_find_me_in_def_contact_test = self.phone.to_s + self.email.to_s
$test_url_and_name_company_56456456__find_me_in_def_contact_test = self.company_name.to_s + self.url_name.to_s
end
def set_user_project
self.user_id = User.current.id
project = Project.new
project.name = "text"
project.identifier = "project" + generate_sufix
self.project_id = project.id if project.save
end
def generate_sufix
Time.new.to_i.to_s + Random.new.rand(1_000_000..9_999_999).to_s
end
end
$ export RAILS_ENV="production"
$ export RAILS_ENV=production
$ ruby script/rails generate redmine_plugin Polls
create plugins/polls/app
create plugins/polls/app/controllers
create plugins/polls/app/helpers
create plugins/polls/app/models
create plugins/polls/app/views
create plugins/polls/db/migrate
create plugins/polls/lib/tasks
create plugins/polls/assets/images
create plugins/polls/assets/javascripts
create plugins/polls/assets/stylesheets
create plugins/polls/config/locales
create plugins/polls/test
create plugins/polls/README.rdoc
create plugins/polls/init.rb
create plugins/polls/config/routes.rb
create plugins/polls/config/locales/en.yml
create plugins/polls/test/test_helper.rb
Redmine::Plugin.register :polls do name 'Polls plugin' author 'John Smith' description 'A plugin for managing polls' version '0.0.1' end

ruby script/rails generate redmine_plugin_model <plugin_name> <model_name> [field[:type][:index] field[:type][:index] ...]
$ ruby script/rails generate redmine_plugin_model polls poll question:string yes:integer no:integer
create plugins/polls/app/models/poll.rb
create plugins/polls/test/unit/poll_test.rb
create plugins/polls/db/migrate/001_create_polls.rb
class CreatePolls < ActiveRecord::Migration
def change
create_table :polls do |t|
t.string :question
t.integer :yes, :default => 0
t.integer :no, :default => 0
end
end
end
$ rake redmine:plugins:migrate Migrating polls (Polls plugin)... == CreatePolls: migrating ==================================================== -- create_table(:polls) -> 0.0410s == CreatePolls: migrated (0.0420s) ===========================================
ruby script/rails console [rails 3] rails console >> Poll.create(:question => "Can you see this poll") >> Poll.create(:question => "And can you see this other poll") >> exit
class Poll < ActiveRecord::Base
def vote(answer)
increment(answer == 'yes' ? :yes : :no)
end
end
ruby script/rails generate redmine_plugin_controller <plugin_name> <controller_name> [<actions>]
$ ruby script/rails generate redmine_plugin_controller Polls polls index vote
create plugins/polls/app/controllers/polls_controller.rb
create plugins/polls/app/helpers/polls_helper.rb
create plugins/polls/test/functional/polls_controller_test.rb
create plugins/polls/app/views/polls/index.html.erb
create plugins/polls/app/views/polls/vote.html.erb
class PollsController 'index' end end
<h2>Polls</h2>
<% @polls.each do |poll| %>
<p>
<%= poll.question %>?
<%= link_to 'Yes', { :action => 'vote', :id => poll[:id], :answer => 'yes' }, :method => :post %> (<%= poll.yes %>) /
<%= link_to 'No', { :action => 'vote', :id => poll[:id], :answer => 'no' }, :method => :post %> (<%= poll.no %>)
</p>
<% end %>
get 'polls', :to => 'polls#index' post 'post/:id/vote', :to => 'polls#vote'

Redmine::Plugin.register :redmine_polls do
[...]
menu :application_menu, :polls, { :controller => 'polls', :action => 'index' }, :caption => 'Polls'
end
menu(menu_name, item_name, url, options={})

Redmine::Plugin.register :redmine_polls do
[...]
permission :polls, { :polls => [:index, :vote] }, :public => true
menu :project_menu, :polls, { :controller => 'polls', :action => 'index' }, :caption => 'Polls', :after => :activity, :param => :project_id
end

def index @project = Project.find(params[:project_id]) @polls = Poll.find(:all) # @project.polls end

permission :view_polls, :polls => :index permission :vote_polls, :polls => :vote
Теперь вы настраивать эти два разрешения для существующих ролей. Конечно, необходимо добавить код в PollsController который сделает эту защиту фактической в соответствии привилегиями текущего пользователя. Для этого нам всего лишь нужно добавить :authorize filter и сделать получение инстансной переменной @project возможной только после отработки данного фильтра Вот как это будет выглядеть для метода #index.class PollsController :index
[...]
def index
@polls = Poll.find(:all) # @project.polls
end
[...]
private
def find_project
# @project variable must be set before calling the authorize filter
@project = Project.find(params[:project_id])
end
end
"en": permission_view_polls: View Polls permission_vote_polls: Vote Polls
project_module :polls do
permission :view_polls, :polls => :index
permission :vote_polls, :polls => :vote
end
Теперь вы можете включать и выключать опросы для различных проектов a.vote { font-size: 120%; }
a.vote.yes { color: green; }
a.vote.no { color: red; }
<%= link_to 'Yes', {:action => 'vote', :id => poll[:id], :answer => 'yes' }, :method => :post, :class => 'vote yes' %> (<%= poll.yes %>)
<%= link_to 'No', {:action => 'vote', :id => poll[:id], :answer => 'no' }, :method => :post, :class => 'vote no' %> (<%= poll.no %>)
<% content_for :header_tags do %>
<%= stylesheet_link_tag 'voting', :plugin => 'polls' %>
<% end %>
<% html_title "Polls" % >
class PollsHookListener < Redmine::Hook::ViewListener
def view_projects_show_left(context = {})
return content_tag("p", "Custom content added to the left")
end
def view_projects_show_right(context = {})
return content_tag("p", "Custom content added to the right")
end
end
require_dependency 'polls_hook_listener'
class PollsHookListener "polls/project_overview" end
Redmine::Plugin.register :redmine_polls do
[ ... ]
settings :default => {'empty' => true}, :partial => 'settings/poll_settings'
end
Отображение которое будет загружено необходимо указать в параметре ключа :partial метода setting вызываемого при регистрации вашего плагина. Форма с настройками вашего плагина будет отображена внутри основного шаблона Redmine содержащего тег формы и кнопку для применения настроек. Параметры вашего плагина могут быть отображены при помощи стандартных элементов HTML форм.
Предупреждение Если два плагина будут иметь одинаковые имя переданное в ключе :partial то настройки одного плагина перепишут настройки другого. По этому старайтесь придумать такие имена которые будут уникальны.
<table>
<tbody>
<tr>
<th>Notification Default Address</th>
<td><input type="text" id="settings_notification_default"
value="<%= settings['notification_default'] %>"
name="settings[notification_default]" >
</tr>
</tbody>
</table>
require File.expand_path(File.dirname(__FILE__) + '/../../../test/test_helper')
require File.expand_path('../../test_helper', __FILE__)
class PollsControllerTest 1
assert_response :success
assert_template 'index'
end
end
$ rake db:drop db:create db:migrate redmine:plugins:migrate redmine:load_default_data RAILS_ENV=test
def test_index @request.session[:user_id] = 2 ... end
def test_index Role.find(1).add_permission! :my_permission ... end
def test_index Project.find(1).enabled_module_names = [:mymodule] ... end
sudo suзатем ставим
apt-get install mysql-server libmysqlclient-dev git-core subversion imagemagick libmagickwand-dev libcurl4-openssl-dev curl curl -L https://get.rvm.io | bash -s stable —ruby=2.0.0выполняем
source /usr/local/rvm/scripts/rvmи дописываем в конец файла .bashrc
source /usr/local/rvm/scripts/rvmустанавливаем apache php5 phpmyadmin
sudo apt-get install apache2 php5 phpmyadminправим порты
vim /etc/apache2/ports.conf
NameVirtualHost *:80 Listen 80заменяем на
NameVirtualHost *:8880 Listen 8880и правим дефолтную настройку
vim /etc/apache2/sites-available/default
<VirtualHost *:80>заменяем на
<VirtualHost *:8880>перезапускаем apache
sudo /etc/init.d/apache2 restartзаходим в phpmyadmin
mkdir /var/data cd /var/data/
svn co http://svn.redmine.org/redmine/branches/2.5-stable redmineхотя я предпочитаю брать не из svn а из git
git clone https://github.com/redmine/redmine.git redmine
cd /var/data/redmine cp config/database.yml.example config/database.yml vim config/database.ymlправим доступы
production: adapter: mysql2 database: redmine host: localhost username: root password: "pass" encoding: utf8 development: adapter: mysql2 database: redmine host: localhost username: root password: "pass" encoding: utf8Внимание: логин без кавычек пароль в кавычках
cp config/configuration.yml.example config/configuration.yml vim config/configuration.yml
production:
email_delivery:
delivery_method: :smtp
smtp_settings:
address: smtp.{server}.ru
port: 25
domain: {server}.ru
authentication: :login
user_name: {login}@{server}.ru
password: {pass}
выполняем bundle (не спутайте bundle c bundler)
bundle installиногда редко но по какойто причине не проходит обычно лечится установкой apt-get install {что-то}-dev здесь google в помощь
bundle exec rake db:migrate bundle exec rake generate_secret_tokenможно попробовать запустить из под webrick
ruby script/rails sесли напишет что - то типа
[2014-06-17 07:34:08] INFO WEBrick 1.3.1 [2014-06-17 07:34:08] INFO ruby 2.0.0 (2014-05-08) [x86_64-linux] [2014-06-17 07:34:08] INFO WEBrick::HTTPServer#start: pid=17023 port=3000пробуем зайти на
gem install passenger --no-ri --no-rdocзапускаем установку (если у вас стоит уже nginx сносите)
passenger-install-nginx-module
Welcome to the Phusion Passenger Nginx module installer, v4.0.45.выбираем 1 вариант
1. This installer will compile and install Nginx with Passenger support.
Which languages are you interested in?
{enter}
Automatically download and install Nginx? 1. Yes: download, compile and install Nginx for me. (recommended)
Please specify a prefix directory [/opt/nginx]:
{enter}
Nginx with Passenger support was successfully installed.
{enter}
конфигурируем nginx
cd ~ git clone git://github.com/jnstq/rails-nginx-passenger-ubuntu.git mv rails-nginx-passenger-ubuntu/nginx/nginx /etc/init.d/nginxправим конфигурацию
vim /opt/nginx/conf/nginx.confкомментим все от server { до его закрывающей скобки } у меня так
# server {
# listen 80;
# server_name localhost;
#
# #charset koi8-r;
#
# #access_log logs/host.access.log main;
#
# location / {
# root html;
# index index.html index.htm;
# }
#
# #error_page 404 /404.html;
#
# # redirect server error pages to the static page /50x.html
# #
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# root html;
# }
#
# # proxy the PHP scripts to Apache listening on 127.0.0.1:80
# #
# #location ~ \.php$ {
# # proxy_pass http://127.0.0.1;
# #}
#
# # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
# #
# #location ~ \.php$ {
# # root html;
# # fastcgi_pass 127.0.0.1:9000;
# # fastcgi_index index.php;
# # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# # include fastcgi_params;
# #}
#
# # deny access to .htaccess files, if Apache's document root
# # concurs with nginx's one
# #
# #location ~ /\.ht {
# # deny all;
# #}
# }
и вставляем
server {
listen 80;
server_name {ваш сервер};
root /var/data/redmine/public;
passenger_enabled on;
client_max_body_size 10m; # Max attachemnt size
}
sudo /etc/init.d/nginx startзаходим проверяем если нужно перенести redmine
bundle install bundle exec rake db:migrate bundle exec rake redmine:plugins bundle exec rake generate_secret_token
#!/usr/bin/env ruby
def allowed_ext?(file)
['jpg', 'JPG', 'gif', 'GIF', 'png', 'PNG'].include?(file.split(".").pop)
end
Dir.open('.').each do |file|
if allowed_ext?(file)
file_downcase = file.downcase
system "mv ./#{file} ./#{file_downcase}"
end
end
Dir.open('.').each do |file|
system "convert #{file} -resize 300 #{file}" if allowed_ext?(file)
end