Rename project in Ruby on Rails 4.0.2 - ruby-on-rails

I'm aware of the Rename plugin for rails (https://github.com/get/Rename), but does anyone know of a way to easily rename a project in Rails 4.0.2 seeing as plugins are deprecated beginning with Rails 4?

Just consider you have used
rails new blog
This will create a blog application. Now if you want to rename the folder blog, just use
$mv blog blog_new
This will just rename the folder and the application will run with no issues as external folder name changes will not affect the application. Else you need to change each file as specified by srt32 but i don't see any specific reason to change project name from inside.

Assuming your app name is my_app you can run something like grep -r 'my_app' . from the root of your project and find all the places where the app name is referenced. It shouldn't be that bad to go update them. The list of places should look something like:
config/application.rb
config/environment.rb
config/environments/development.rb
config/environments/test.rb
config/environments/production.rb
config/initializers/secret_token.rb
config/routes.rb
Rakefile

Enter following commands
$ rails new ProjectToRename
$ cd ProjectToRename
$ grep -ri 'project_?to_?rename'
Finally done.
You'll need to rename the top-level directory yourself:
$ cd ..
$ mv ProjectToRename SomeNewName

I've written the following script to do just that. You can see it also at https://gist.github.com/danielpclark/8dfcdd7ac63149323bbc
#!/usr/bin/ruby
# Rename Rails Project (File: rename_rails)
# Copyright 6ft Dan(TM) / MIT License
# Check the config/application.rb for capital usage in project name by model OldProjectName
# Usage: rename_rails OldProjectName NewAwesomeName
# Replace string instances of project name
`grep -lR #{ARGV[0]} | xargs sed -i 's/#{ARGV[0]}/#{ARGV[1]}/g'`
`grep -lR #{ARGV[0].downcase} | xargs sed -i 's/#{ARGV[0].downcase}/#{ARGV[1].downcase}/g'`
# Rename Rails directory if it exists
if File.directory?(ARGV[0])
`mv #{ARGV[0]} #{ARGV[1]}`
drc = ARGV[1]
elsif File.directory?(ARGV[0].downcase)
`mv #{ARGV[0].downcase} #{ARGV[1]}`
drc = ARGV[1]
end
# Delete temporary files (helps prevent errors)
drc ||= ''
if ['cache','pids','sessions','sockets'].all? {
|direc| File.directory?(File.join(drc,'tmp', direc)) }
FileUtils.rm_rf(File.join(drc,'tmp'))
end
And I've created a howto video on YouTube. http://youtu.be/dDw2RmczcDA

Related

Why is there ```No value provided for required arguments 'app_path'``` when I try to create a rails app?

(this is my first post, sorry if i make a mistake),
In Iterm2 I put :
rails _5.2.3_ new -d postgresql
And the terminal answers:
No value provided for required arguments 'app_path'
I opened the .zshrc file and tried to figure out if the problem comes from this file and searched for the keyword PATHbut couldn't figure out if a path is wrong or not. Does the problem is on the .zshrc file ? Where is the problem and how to solve it ?
Here is my .zshrc file
# export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation.
export ZSH="/Users/thibaultguichard/.oh-my-zsh"
# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes
ZSH_THEME="simple"
# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in ~/.oh-my-zsh/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to automatically update without prompting.
# DISABLE_UPDATE_PROMPT="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS=true
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load?
# Standard plugins can be found in ~/.oh-my-zsh/plugins/*
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(
git
bundler
dotenv
osx
rake
rbenv
ruby
zsh-syntax-highlighting
zsh-autosuggestions
)
source $ZSH/oh-my-zsh.sh
# User configuration
# export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
# export PATH="$PATH:$HOME/.rvm/bin"
# SYSTEM ALIAS
alias cls='clear' # Clear the terminal
alias c='clear' # Clear the terminal
alias h='history' # Print bash command history
alias ll='ls -l' # List files in a list
alias la='ls -al' # List files in a list with hidden files
# GIT ALIAS
alias gitalias='alias | grep git' # Show all alias for git (if you have OH MY ZSH you have lots of other aliases)
alias gs='git status' # Show the working tree status
alias gcl='git clone' # Clone a repository into a new directory
alias gpush='git push' # Update remote refs along with associated objects
alias gpull='git pull' # Fetch from and integrate with another repository or a local branch
alias ga='git add' # Add file contents to the index
alias gcm='git commit -m' # Record changes to the repository
alias gco='git checkout' # Switch branches or restore working tree files
alias gbr='git branch' # List, create, or delete branches
alias glog='git log' # Show commit logs
alias greset='git reset' # Reset current HEAD to the specified state
# BUNDLE ALIAS
alias bundlealias='alias | grep bundle' # Show all alias for bundle
alias bi='bundle install' # Install the current environment to the system
alias bl='bundle list' # List all gem in GEMFILE and version
alias bu='bundle update' # Update the current environment (update gem)
alias ba='bundle add' # Command for add multiple gem in gemfile and launch a bundle update
# HEROKU ALIAS
alias herokualias='alias | grep heroku' # Show all alias for Heroku
alias hrdbs='heroku run rake db:seed'
alias hrdbm='heroku run rails db:migrate'
alias hrc='heroku create'
alias hrrc='heroku run rails console'
alias hrbi='heroku run bundle install'
alias hrupdate='heroku update' # Update the Heroku CLI
alias hrpsql='heroku psql' # Open a psql shell to the database
alias hrlogs='heroku logs' # Display recent log output
alias hrlog='heroku logs' # Display recent log output
# APT ALIAS
alias aptalias='alias | grep apt' # show all alias for apt
alias update='sudo apt update -y' # Update list of available packages
alias upgrade='sudo apt upgrade -y' # Upgrade the system by installing/upgrading packages
alias full-upgrade='sudo apt full-upgrade -y' # Upgrade the system by removing/installing/upgrading packages
alias dist-upgrade='sudo apt dist-upgrade -y' # Upgrade your distributtion system with sudo and ask yes
alias autoremove='sudo apt autoremove' # Remove automatically all unused packages
# RAILS ALIAS
alias railsalias='alias | grep rails' # Show all alias for rails
### RAILS CREATION
alias nr='rails _5.2.3_ new'
alias nrp='rails _5.2.3_ new -d postgresql'
### RAILS OTHER
alias rc='rails console'
alias rd='rails destroy'
alias rp='rails plugin'
alias ru='rails runner'
alias rs='rails server'
alias rsd='rails server --debugger'
alias rr='rails routes'
### RAILS GENERATE
alias rg='rails generate'
alias rgmigration='rails generate migration'
alias rgmodel='rails generate model'
alias rgscaffold='rails generate scaffold'
alias rgc='rails generate controller'
### RAILS DATABASE
alias rdb='rails dbconsole' # Database console in the database of your Rails APP
alias rdbd='rails db:drop'
alias rdbc='rails db:create'
alias rdbs='rails db:seed'
alias rdbm='rails db:migrate'
alias rdbms='rails db:migrate status'
alias rdbr='rails db:rollback'
#OTHERS ALIAS
alias path='echo -e ${PATH//:/\\n}' # Print all PATH environnement in a list
alias now='date +"%T"' # Get the time now
alias nowdate='date +"%d-%m-%Y"' # Get the Date
alias vi='vim'
alias svim='sudo vim' # Launch Vim with sudo
alias edit='vim'
You don't specify a name for your new project.
Try with rails _5.2.3_ new NameOfTheApp -d postgresql
It should work. (:

.gitignore not ignoring files

Here is my .gitignore file:
# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
# git config --global core.excludesfile '~/.gitignore_global'
# Ignore bundler config.
/.bundle
# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-journal
# Ignore all logfiles and tempfiles.
/log/*
!/log/.keep
/tmp
# Ignore application configuration
/config/application.yml
/config/application.yml.bak
*.bak
Now, my repository is at https://github.com/rmohan80/learn-rails
Why would my latest commit -- "add configuration for email" add Readme.rdoc.bak but ignore .gitignore.bak
Any clues?
The star character does do match files beginning with a period.
You can add .*.bak to ignore them in your case or you can change the glob option in your shell :
# capture dot file
shopt -s dotglob
# do git stuff here
# stop capturing dot file
shopt -u dotglob
A similar problem solved here : https://stackoverflow.com/a/19365350
You have to checkout the HEAD, so that your repository looks unmodified. Then run the following:
$ echo '*.*.bak' >> .gitignore
To exclude files that are formatted like README.md.bak.
And run
$ echo '**/*.bak' >> .gitignore
to exclude files that are formatted like README.bak anywhere in the tree below the current directory.
Having .bak.bak files is something you don't want.

Rake task to change all occurances of a method in a project

I am trying to write a rake task to rename all occurrences of a method in a ruby project. I have achieved this using the following command from the command line.
Basically
retention.group_by('bla').count
needs to be changed to
retention.group_by('bla').size
I managed to achieve this uisng the following from the command line
find . -name \*.rb -exec ruby -i -p -e "gsub(/(group_by(\(([^\)]+)\))).count/, '\1.size')" \;
I am now trying to do this from a rake task to make it straight forward to change in all our projects. Which is the easiest / most elegant way to do this ? Think I am close, its just selecting all files in a project directory I am stuck on.
This did the trick
namespace :rename do
task :gb_count_rename do
Dir.glob("**/*.rb").each do |file_name|
text = File.read(file_name)
content = text.gsub(/(group_by(\(([^\)]+)\))).count/, '\1.size')
File.open(file_name, "w") { |file| file << content }
end
end
end

How to execute 5 different ruby files in series

I'm new to ruby and I'm trying to run 5 different files in a folder. I'd like to execute them all in series mean one after another.
the list of my files are:
Scripts/aaa. rb
Scripts/bbb. rb
Scripts/ccc. rb
Scripts/ddd. rb
Scripts/eee. rb
My script should run the aaa.rb first and then rest
Do as below using Dir::chdir, Dir::glob:
Dir.chdir("path/to/the/.rb files") do |path|
Dir.glob("*.rb").sort.each do |name|
system("ruby #{name}")
end
end
create another ruby script to run them in order
["aaa", "bbb", "ccc", "ddd", "eee"].each do |name|
system("ruby #{name}.rb") #give the full path of the file here
end
Depending on your OS, you can use a batch file, or a shell script. In either case, that's exactly their purpose. Assuming you have the executable bit set on the files:
On *nix or Mac OS:
#!/bin/sh
Scripts/aaa.rb
Scripts/bbb.rb
Scripts/ccc.rb
Scripts/ddd.rb
Scripts/eee.rb
as a simplistic script.
For something a bit more "DRY":
#!/bin/sh
pushdir Scripts
for i in aaa bbb ccc ddd eee
do
$i.rb
done
popdir
If the executable-bit isn't set, precede the name of the file with the path to your Ruby executable, something like:
/usr/local/bin/ruby Scripts/aaa.rb
There are a lot of other ways to point to the Ruby executable, so your mileage might vary.

Chef deploy_resource private repo, ssh deploy keys and ssh_wrapper

I'm having loads of trouble getting my Chef recipe to clone a private repo. Well, I had it working yesterday but after 'cheffin' my Vagrant box half a dozen times, I've broken it. I'm a Chef newbie as you may guess.
Following the deploy_resource guide here, I've created my deploy.rb recipe (shortened):
deploy_branch "/var/www/html/ps" do
repo git#github.com:simonmorley/private-v2.git
ssh_wrapper "/tmp/.ssh/chef_ssh_deploy_wrapper.sh"
branch "rails4"
migrate false
environment "RAILS_ENV" => node[:ps][:rails_env]
purge_before_symlink %w{conf data log tmp public/system public/assets}
create_dirs_before_symlink []
symlinks( # the arrow is sort of reversed:
"conf" => "conf", # current/conf -> shared/conf
"data" => "data", # current/data -> shared/data
"log" => "log", # current/log -> shared/log
"tmp" => "tmp", # current/tmp -> shared/tmp
"system" => "public/system", # current/public/system -> shared/system
"assets" => "public/assets" # current/public/assets -> shared/assets
)
scm_provider Chef::Provider::Git # is the default, for svn: Chef::Provider::Subversion
notifies :restart, "service[ps]"
notifies :restart, "service[nginx]"
end
In defaults, I have the following to create the dirs etc.
directory "/tmp/.ssh" do
action :create
owner node[:base][:username]
group node[:base][:username]
recursive true
end
template "/tmp/.ssh/chef_ssh_deploy_wrapper.sh" do
source "chef_ssh_deploy_wrapper.sh.erb"
owner node[:base][:username]
mode 0770
end
# Put SSH private key to be used with SSH wrapper
template "/tmp/.ssh/id_deploy" do
source "id_rsa.pub.erb"
owner node[:base][:username]
mode 0600
end
And in the wrapper:
#!/bin/sh
exec ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i "/tmp/.ssh/id_deploy" "$#"
And I have created a public key and uploaded this to github.
When I deploy the recipe, it gives me an error:
deploy_branch[/var/www/html/ps] action deployEnter passphrase for key '/tmp/.ssh/id_deploy':
Obvs I don't have a password set... The private key must therefore be missing..
Just by chance, I removed the id_deploy key from the recipe, deleted the folders and ran it again. Low and behold, it started working... The reason being that the id_rsa.pub && id_rsa files were in /root/.ssh from when I manually generated them to test.
I don't understand what I'm doing wrong here. My questions are therefore:
Do I need a private and public key on each node I deploy to? The docs don't mention this.
Should this not be deploying as non-root user? I have set a user in my roles file..
Why is the ssh_wrapper not doing what it's supposed to
It took a good couple of days to figure this out properly.
Just to clarify, this is what I did to fix it. I do not know if it's correct, but it works for me.
Generate a set of public and private keys following this tutorial.
Add the public key to the Github repo that you want to clone.
Create a template in my default recipe which includes both the public and private keys. See below.
Created the relevant templates for the pub and private keys.
Created the chef_ssh_deploy_wrapper.sh.erb file (see below)
Created a deploy.rb recipe (see below)
Uploaded and added the recipes to my role. Ran chef-client.
Hey presto! Sit back with a beer and watch your repo. smartly cloned into your dir.
The templates are as follows:
Create the directories and templates:
template "/tmp/.ssh/chef_ssh_deploy_wrapper.sh" do
source "chef_ssh_deploy_wrapper.sh.erb"
owner node[:base][:username]
mode 0770
end
template "/home/#{node[:base][:username]}/.ssh/id_rsa.pub" do
source "id_rsa.pub.erb"
owner node[:base][:username]
mode 0600
end
template "/home/#{node[:base][:username]}/.ssh/id_rsa" do
source "id_rsa.erb"
owner node[:base][:username]
mode 0600
end
Create an ssh wrapper chef_ssh_deploy_wrapper.erb
#!/bin/sh
exec ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i "/home/#{node[:base][:username]}/.ssh/id_rsa" "$#"
(Make sure you use the private key here or it will fail)
Finally the deploy.rb recipe:
deploy_branch node[:my_app][:deploy_to] do
repo node[:base][:repository]
ssh_wrapper "/tmp/.ssh/chef_ssh_deploy_wrapper.sh"
branch "rails4"
user node[:base][:username]
group node[:base][:username]
rollback_on_error true
migrate false
environment "RAILS_ENV" => node[:my_app][:environment]
purge_before_symlink %w{conf data log tmp public/system public/assets}
create_dirs_before_symlink []
symlinks(
"config" => "config",
"data" => "data",
"log" => "log",
"tmp" => "tmp",
"system" => "public/system",
"assets" => "public/assets"
)
scm_provider Chef::Provider::Git # is the default, for svn: Chef::Provider::Subversion
before_restart do
system("su #{node[:base][:username]} -c 'cd #{node[:my_app][:deploy_to]}/current && /usr/bin/bundle install'") or raise "bundle install failed"
system("su #{node[:base][:username]} -c 'RAILS_ENV=production /usr/local/bin/rake assets:precompile'")
end
notifies :restart, "service[my_app]"
notifies :restart, "service[nginx]"
end
The before restart has since been replaced as we were initially compiling ruby from source but decided to use rvm in the end. Much easier for multi-user installations.
NB: I'm deploying as an sudo user, if you're doing so as root (avoid this), use the /root/.ssh path instead.
I took much inspiration from this article.
Good luck, I hope this helps someone.
Your question doesn't have a link to to the deploy_resource source, so I can't be sure if this will apply, but if it uses a git resource underneath, the following might be helpful...
As described in this answer to a similar question, you can avoid creating extra script files to go with each SSH key by adding the SSH command as an "external transport" part of the repository URL:
git "/path/to/destination" do
repository "ext::ssh -i /path/to/.ssh/deployment_key -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no git#github.com %S /my_name/some_repo.git"
branch "master"
...
end

Resources