Rails 4 - cannot get ENV variables in production - ruby-on-rails-4

I am trying to get my ENV variables in production mode ...
but now way .. cannot reach the server ... the SECRET_KEY_BASE is not found ... if I hardcode it , then go trouble w the database creds, and if I hardcode them, got trouble w the SMTP creds...
this means that no ENV[] variables cannot be reached ...
I added the gemfile to get it in :production environment, and bundled it
gem 'dotenv-rails', :groups => [:development, :test, :staging, :production]
my .env file is present in my remote server ( Ubuntu 14 - w .rbenv Ruby 2.0 , Rais 4.2 )
cat /var/www/workshop/shared/.env
SECRET_KEY_BASE=106063d5146566142b6aa4782b874115c73a61ac2505f11f8e
DATABASE_USER_NAME=myself
DATABASE_PASSWORD=mydbpwd
MAILGUN_SMTP_SERVER=smtp.mailgun.org
MAILGUN_SMTP_USER_NAME=postmaster#mydomain.com
MAILGUN_SMTP_PASSWORD=2fc998a7399999999a264b88c
MAILGUN_SMTP_DOMAIN=mydomain.com
I set my secrets.yml file on the remote server
cat secrets.yml
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
I set my database.yml
cat database.yml
production:
adapter: postgresql
database: workshop
encoding: unicode
pool: 5
username: <%= ENV['DATABASE_USER_NAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
and I updated my config/environments/production.rb w smtp creds
cat production.rb
.....
# SMTP settings for mailgun
config.action_mailer.smtp_settings = {
:port => 587,
:address => ENV['MAILGUN_SMTP_SERVER'],
:user_name => ENV['MAILGUN_SMTP_USER_NAME'],
:password => ENV['MAILGUN_SMTP_PASSWORD'],
:domain => ENV['MAILGUN_SMTP_DOMAIN'],
:authentication => :plain,
:enable_starttls_auto => true
}
...

Finally I gave up w .dotenv in production...
I resolved using Rails 4.1 secrets.yml...
as I am deploying w capistrano 3 ,
- I use the gem capistrano-upload-config
- I created : secrets.production.yml , database.production.yml, configuration.production.yml
- I added in my capistrano deploy.rb
set :config_files, %w{config/database.yml config/secrets.yml config/application.yml}
set :linked_files, %w{config/database.yml config/secrets.yml config/application.yml}
capistrano uploads these productions files from the local .production files and link them... so
the server database.yml is loaded/linked (from local database.production.yml)
the server secrets.yml is loaded/linked (from local secrets.production.yml)
the server application.yml is loaded/linked (from local application.production.yml)
regarding the production.rb SMTP settings , I use the secrets file :
:address => Rails.application.secrets.mailgun_smtp_server,
...
all these files are in .gitignore

Related

Capybara::Poltergeist Status error, failed to reach server

I am trying to make some tests with Rspec/Capybara/Poltergeist on my Rails 4 application, Phantomjs is installed (version 2.2.1), but I always get this error :
Failure/Error: visit(perfect_landing_page_path)
Capybara::Poltergeist::StatusFailError:
Request to 'http://127.0.0.1:49623/path' failed to reach server, check DNS
and/or server status
The test i'm working on :
require 'rails_helper'
RSpec.feature 'Subscription', :type => :feature do
let!(:plan) { create(:plan) }
let!(:landing_page) { create(:landing_page) }
before(:each) { landing_page.default_plan = plan }
describe 'landing_page#perfect_show' do
scenario 'form display', js: true do
plan_2 = create(:plan)
plan_3 = create(:plan)
landing_page.plans << plan_2
landing_page.plans << plan_3
visit(perfect_landing_page_path)
expect(page).to have_css(".start-now", count: 3)
first(".start-now").click
expect(page).to have_css("#new_user")
end
end
end
My Gemfile looks like this :
gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
gem 'guard-rspec'
group :test do
gem 'database_cleaner'
gem 'capybara'
gem 'capybara-screenshot'
gem 'poltergeist'
gem 'selenium-webdriver'
gem 'shoulda-matchers', require: false
gem 'show_me_the_cookies'
end
My spec/support/capybara.rb file :
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require "capybara/poltergeist" # Add this line to require poltergeist
require 'selenium-webdriver'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {:js_errors => false, :default_max_wait_time => 30, :timeout => 30, phantomjs_options: [
'--load-images=no',
'--ignore-ssl-errors=true',
'--ssl-protocol=any']})
end
Capybara.register_driver :poltergeist_debug do |app|
Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.configure do |config|
config.javascript_driver = :poltergeist
config.ignore_hidden_elements = true
config.default_max_wait_time = 30
end
My spec_helper.rb file :
require 'capybara/rspec'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
Did someone encounter this problem before ? Does anyone have a solution for this ? I have been banging my head for days looking on the web...
Thank you very much.
PS : it works fine on my friend's mac (Yosemite or El Capitan), just not on mine.
I was having this problem in CI (CodeShip).
Adding a call to bundle exec rake assets:precompile at the end of the setup commands seemed to fix it:
CodeShip CI Setup Commands:
rvm use 2.3.4 --install
bundle install
export RAILS_ENV=test
bundle exec rake db:schema:load
bundle exec rake assets:precompile
Also had a whitelist per #agbodike but in the rails_helper.rb
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
I had the same issue and it was due to a 3rd party script timing out. You can prevent loading of 3rd party scripts with a blacklist. For example:
config.before(:each, js: true) do
page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end
would prevent any URL starting with http://use.typekit.net from being called for each test that uses the js driver. More information can be found at:
https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls
Alternatively you can use a whitelist:
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
which will block all requests not to 127.0.0.1
I placed the configuration in spec/feature_helper.rb to ensure it was only set for feature specs.
You can avoid these by precompile the assets before tests.
And the code is:
RSpec.configure do |config|
config.before :all do
ENV['PRECOMPILE_ASSETS'] ||= begin
case self.class.metadata[:type]
when :feature, :view
STDOUT.write "Precompiling assets..."
require 'rake'
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
STDOUT.puts " done."
Time.now.to_s
end
end
end
end
more info

Error (upload image) after deploy using capistrano rails 4

Yesterday i tried to deploy my rails app to my own server. For deploy, i have followed gorails tutorial -> https://gorails.com/deploy/ubuntu/14.04. After deployed, finally my rails app has running live. But i have a problem when i try to create room module with image, i get error like this
We're sorry, but something went wrong.
If i create room without image, it success. I'm sure that i can't upload image.
gem 'paperclip'
room.rb
has_attached_file :image, :styles => { :for_index => "336x227>", :thumb => "150x150>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
deploy.rb
lock '3.1.0'
set :application, 'hotelxxxxx'
set :repo_url, 'git#bitbucket.org:xxxxxx/hotelxxxxx.git'
set :deploy_to, '/home/xxxxxx/hotelxxxxx'
set :linked_files, %w{config/database.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
execute :touch, release_path.join('tmp/restart.txt')
end
end
after :publishing, 'deploy:restart'
after :finishing, 'deploy:cleanup'
end
How to fix that?
The first step to troubleshoot this issue would be to look at the Rails log on your server. It should be in the log/production.log file. Having the actual error message in the log would make it a lot easier to help you figure this out.
Finally image uploaded !! I see error from nginx error.log => 'Paperclip::Errors::NotIdentifiedByImageMagick'. After that i try to re-install imagemagick from https://www.enovate.co.uk/web-design-blog/2015/02/25/how-to-install-imagemagick-from-source-on-ubuntu-14.04/
Imagemagick re-install succeed and open config/application.rb in my rails app
config/application.rb
# add line
Paperclip.options[:command_path] = "/usr/local/bin/identify"
Deploy again

Rails 4: How to add ENVIRONMENT VARIABLES on Ubuntu 14.04 using RVM?

Right now I'm trying to deploy my Ruby on Rails app to a Virtual Machine on Windows Azure running Ubuntu but I can fix de set environment variables error as below describe.
I have done added variables to my .bashrc and now in /etc/environment but the error is the same:
App 1227 stderr: [ 2015-10-06 04:10:57.3814 1352/0x9020d38(Worker 1) utils.rb:86 ]: *** Exception RuntimeError in Rack application object (Missing `secret_to$
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:534:in `validate_secret_$
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:246:in `env_config'
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/engine.rb:514:in `call'
App 1227 stderr: from /home/deploy/apps/matching_people/shared/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:165:in `call'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:94:in `process_request'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:151:in `accept_and_process_next_request'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:112:in `main_loop'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
App 1227 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:112:in `block in create_thread_and_abort_on_exception'
[ 2015-10-06 04:10:57.3819 988/b5efeb40 age/Cor/Req/Utils.cpp:95 ]: [Client 1-1] Sending 502 response: application did not send a complete response
This is my sudo nano /etc/environment file:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
export SECRET_KEY_BASE=2da0d3f0bfd7b9b05110bfad512f42df2d2bb2ef715c4e831caba96a9c0b2141fbfa718dff2f5daf916cd70a70afd1f24df49884c561fbbaf364b36652b2c7d1
ruby -e 'p ENV["SECRET_KEY_BASE"]'
export MATCH_PEOPLE_DATABASE_PASSWORD=2015deployer
ruby -e 'p ENV["MATCH_PEOPLE_DATABASE_PASSWORD"]'
And when I run echo $SECRET_KEY_BASE or echo $MATCH_PEOPLE_DATABASE_PASSWORD I got the exact data.
deploy#vmw-ubuserver:~$ echo $SECRET_KEY_BASE
2da0d3f0bfd7b9b05110bfad512f42df2d2bb2ef715c4e831caba96a9c0b2141fbfa718dff2f5daf916cd70a70afd1f24df49884c561fbbaf364b36652b2c7d1
deploy#vmw-ubuserver:~$ echo $MATCH_PEOPLE_DATABASE_PASSWORD
2015deployer
But I still getting the same error in production, I'm using RVM, Capistrano, Passenger and NGINX on Ubuntu 14.04.
My database.yml :
production:
adapter: mysql2
encoding: utf8
pool: 5
host: localhost
database: matchpeople_production
username: deployer
password: <%= ENV['MATCH_PEOPLE_DATABASE_PASSWORD'] %>
My secrets.yml :
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
secret_token: <%= ENV["SECRET_KEY_BASE"] %>
Any kind of help?
Looking and looking for the correct answer I have been trying too many options but I didn't make it works fine.
So, suddenly I found I solution while I was testing some configurations found on google.
It is simple, just:
Add the next lines:
export SECRET_KEY_BASE=3aa7e349bh345h245hi23452345h234ih52i3u45h$
export MATCH_PEOPLE_DATABASE_PASSWORD=your_pass_here
# Uncomment these lines and restart the server to validate if the variables are read correctly
#ruby -e 'p ENV["SECRET_KEY_BASE"]'
#ruby -e 'p ENV["MATCH_PEOPLE_DATABASE_PASSWORD"]'
At the end of the files below:
sudo nano ~/.bash_profile
sudo nano /etc/environment
If you want you can uncomment the last two lines in ~/.bash_profile and restart your server and when you login to it again, you will see the value of the ENVIRONMENT VARIABLES before your promt as in the picture below.
I recommend you to keep those lines commented do it just for validate and then comment them again.
If you have any question, please leave a comment!
Hope it could be useful.
From my experience, there is no secret_token needed in secrets.yml for Ruby RVM.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
I think to solve the problem, remove the second line from your production: section
In case you need to add environment variables to RVM, edit
# /etc/profile.d/appspecific.sh
add something like
export GEM_PATH=/usr/local/rvm/gems/ruby-1.9.3-p551:/usr/local/rvm/gems/ruby-1.9.3-p551#global
export GEM_HOME=/usr/local/rvm/gems/ruby-1.9.3-p551
Good luck!

Rails 4 I18n - missing translation after adding new locale file

Currently I have some locales subdirectories , which are correctly set in the configuration
config/application.rb
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
I have already 2 locales files , and I can get easily the translations :
config/locales/admin/dashboard.en.yml
en:
dashboard:
title: Dashboard
config/locales/admin/dashboard.fr.yml
fr:
dashboard:
title: Tableau de bord
irb(main):014:0> I18n.locale = :en
=> :en
irb(main):015:0> I18n.t("dashboard.title")
=> "Dashboard"
irb(main):016:0> I18n.locale = :fr
=> :fr
irb(main):017:0> I18n.t("dashboard.title")
=> "Tableau de bord"
Now I added 2 other locales files ( quite similar to previous ones...) into the SAME subdirectory 'locales/admin'
# =============
config/locales/admin/sheet.en.yml
en:
sheet:
title: Sheet
config/locales/admin/sheet.fr.yml
fr:
sheet:
title: Table
I RESTARTED the server ... and tried wo success to get the new added translations
irb(main):010:0> I18n.locale = :en
=> :en
irb(main):011:0> I18n.t("sheet.title")
=> "translation missing: en.sheet.title"
irb(main):012:0> I18n.locale = :fr
=> :fr
irb(main):013:0> I18n.t("sheet.title")
=> "translation missing: fr.sheet.title"
translations missing in BOTH languages? so I guess something is wrong in the subdirectories definition in the application.rb config file, as I checked the Rails.application.config.i18n.load_path ,a dn the newly added files ARE NOT in the path ..
"..../config/locales/admin/dashboard.en.yml",
"..../config/locales/admin/dashboard.fr.yml",
but not
"..../config/locales/admin/sheet.en.yml",
"..../config/locales/admin/sheet.fr.yml",
thanks for suggestions
It seems this issue has been already detected and it's related to the 'spring' process..
# https://github.com/rails/spring/issues/408
# rafaelfranca May 28
I think you got this error because you added the locale file after you
started the spring process for your environment, so when you add the
file it is not loaded inside the spring process. When you change the
application.rb the spring process is reloaded and your locale is now
working.
I changed one line ( added one blank line ...) in the application.rb than I restarted the server , and the new translations are found
rafael stated the rails console should restart the spring
Any rails command starts springs. rails console, rails generate,
rails server. You can stop the spring process with spring stop.
so, after ADDING a new locale file, better stopping spring before restarting the server
spring stop
rails server ( or rails console )
Change application.rb => Restart the Rails server
I would like to add that any time you make any change to application.rb you must restart the server for the change to take effect, not just the i18n component.

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

My ruby on rails action mailer runs all good in development environment, but in production environment, it keeps throw:
ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
My development config is
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => xxx,
:address => 'smtp.example.org',
:user_name => 'xxx#example.com',
:password => 'xxxxxxxx',
:domain => 'xxxxxx.example',
:authentication => :plain,
}
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
My production config is
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => 587,
:address => 'smtp.example.org',
:user_name => 'xxx#example.com',
:password => 'xxxxxx',
:domain => 'example.com',
:authentication => :plain,
}
config.action_mailer.default_url_options = { :host => 'example.com' }
My other environments are:
ruby 2.1.1
rails 4.0.3
sidekiq
devise
devise-async
I have tried:
Add the following in a initializer file
ActionMailer::Base.default_url_options[:host] = "example.com"
This answer here
Neither of them works.
In the end I added the following with the correct value to each environment file:
test.rb / development.rb / production.rb
Devise 3.2.x - 4.x.x
Rails 4.1.x && Rails 4.2.x && Rails 5.x.x
Thanks to maudulus
# Default Mailer Host
Rails.application.routes.default_url_options[:host] = 'domain.example'
Try restarting the server. Even in Rails 4.1 the config is not reparsed without a restart.