Я работаю над веб-приложением, которое содержит основные элементы веб-приложения CMS.Пользователи могут клонировать репозиторий, запускать сервер rails и переходить на страницу, которая позволяет им переименовывать приложение из текущего имени, «framework», во что угодно.После небольшой дискуссии здесь я решил поместить код переименования в мой контроллер (в отличие от файла rake).Но моя проблема в том, что моему контролеру сложно понять, что происходит.Вот так выглядит мой взгляд.
<h1>Rails Framework</h1>
<%= form_tag "/namer" do %>
<%= text_field_tag "appname" %>
<%= submit_tag "Name Your App" , :action => 'create' %>
<% end %>
А это мой контроллер.
class NamerController < ApplicationController
def index
render('new')
end
def new
@appname = Namer.new
end
def create
@appname = Namer.new(params[:appname])
#first, change any instances of the term "framework" to the new name of the app
file_names = ['config/environments/test.rb', 'config/environments/production.rb',
'config/environment.rb']
file_names.each do |file_name|
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("Framework", @appname) }
end
#next,change the rootpath away from namer#new
file_name ='config/routes.rb'
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("namer#new", "pages#home") }
flash[:notice] = "Enjoy your app."
render('pages/home')
end
end
У меня также есть модель под названием renamer.Это очень просто.Я удалил «
class Namer
end
Моя проблема в том, что когда я ввожу новое имя в форму, rails возвращает сообщение об ошибке:
TypeError in NamerController#create. Can't convert Namer into String.
Я не уверен, почему так хочется превратить Namer в строку, так как я думал, что она использует только переменную @appname в качестве строки.Любые идеи о том, почему это не удается?
ОБНОВЛЕНИЕ: Итак, я внес некоторые изменения в исходный код и вот как он выглядит сейчас.По какой-то причине код успешно запустился и изменил имя некоторых файлов, которые он должен.
class NamerController < ApplicationController
def index
render('new')
end
def new
end
def create
#first, change any instances of the term "framework" to the new name of the app
file_names = ['config/environments/test.rb', 'config/environments/production.rb',
'config/environment.rb']
file_names.each do |file_name|
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("Framework", params[:appname]) }
end
#next,change the rootpath away from namer#new
file_name ='config/routes.rb'
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("namer#new", "pages#home") }
File.open(file_name, "w") { |file| file << text.gsub("post '/namer' =>
'namer#create'", "") }
flash[:notice] = "Enjoy your app."
redirect_to(root_path)
end
end
По какой-то причине, когда код был полу-успешным, он в итоге удалил весь файл congig / environment / test.rb, который выглядит следующим образом.
Framework::Application.configure do
config.cache_classes = true
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
config.whiny_nils = true
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
config.assets.allow_debugging = true
end
Я случайно переместился по одной из строк в папке маршрутов, что каким-то образом не позволило запустить код переименования.(Понятия не имею почему).Поэтому я полагаю, что это может быть связано с проблемой очистки файла test.rb от всего текста.Вот мой файл route.rb.
Framework::Application.routes.draw do
resources :users
resources :sessions, :only => [:new, :create, :destroy]
match '/signup', :to => 'users#new'
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/contact', :to => 'pages#contact'
match '/about', :to => 'pages#about'
match '/help', :to => 'pages#help'
post '/namer' => 'namer#create'
root :to => "namer#new"
match ':controller(/:action(/:id(.:format)))'
end
РЕШЕНИЕ: Это то, как мой метод Create в итоге выглядел.И теперь это работает так, как я хотел.
def create
#first, change any instances of the term "framework" to the new name of the app
file_names = ['config/environments/test.rb', 'config/environments/production.rb',
'config/environment.rb']
file_names.each do |file_name|
text = File.read(file_name)
File.open(file_name, "w") {|file| file << text.gsub("Framework", params[:appname])}
end
#next,change the rootpath away from namer#new
file_name ='config/routes.rb'
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("namer#new", "pages#home") }
file_name ='config/routes.rb'
text = File.read(file_name)
File.open(file_name, "w") { |file| file << text.gsub("post '/namer' =>
'namer#create'", "") }
flash[:notice] = "Enjoy your app."
redirect_to(root_path)
end