What's the proper way to have envionrment variables inserted into my configuration file? - configuration

Using Rails 5.0.1. I have this in my config/initializers/sidekiq.rb file ...
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://#{ENV['REDIS_PORT_6379_TCP_ADDR']}:#{ENV['REDIS_PORT_6379_TCP_PORT']}/12', namespace: "sidekiq_app_name_#{ENV['RAILS_ENV']}" }
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://#{ENV['REDIS_PORT_6379_TCP_ADDR']}:#{ENV['REDIS_PORT_6379_TCP_PORT']}/12', namespace: "sidekiq_app_name_#{ENV['RAILS_ENV']}" }
end
Although I have the envionrment variables defined in my system, when I attempt to start my server, I get these errors ...
/Users/davea/.rvm/gems/ruby-2.4.0/gems/activesupport-5.0.2/lib/active_support/dependencies.rb:287:in `load': /Users/davea/Documents/workspace/myproject/config/initializers/sidekiq.rb:2: syntax error, unexpected tCONSTANT, expecting '}' (SyntaxError)
{ENV['REDIS_PORT_6379_TCP_ADDR']}:#{ENV['REDIS_PORT_6379_TCP
^
/Users/davea/Documents/workspace/myproject/config/initializers/sidekiq.rb:2: syntax error, unexpected tCONSTANT, expecting keyword_end
{ENV['REDIS_PORT_6379_TCP_PORT']}/12', namespace: "sidekiq_a
^
/Users/davea/Documents/workspace/myproject/config/initializers/sidekiq.rb:2: syntax error, unexpected '}', expecting end-of-input
pp_name_#{ENV['RAILS_ENV']}" }
What's the proper way to insert environment variables into my configuration file?

You can use the gem figaro:
gem "figaro"
How to use it, in the readme.txt explain very easly:
config/application.yml
stripe_api_key: "sk_live_dSqzdUq80sw9GWmuoI0qJ9rL"
ENV["stripe_api_key"] # => "sk_live_dSqzdUq80sw9GWmuoI0qJ9rL"
ENV.key?("stripe_api_key") # => true
ENV["google_analytics_key"] # => nil
ENV.key?("google_analytics_key") # => false
Figaro.env.stripe_api_key # => "sk_live_dSqzdUq80sw9GWmuoI0qJ9rL"
Figaro.env.stripe_api_key? # => true
Figaro.env.google_analytics_key # => nil
Figaro.env.google_analytics_key? # => false

Related

Why key type ecdsa-sha2-nistp256 is unsupported?

I'am trying to use ruby gem net-ssh and receive the error described bellow
jruby-9.1.15.0 :001 > require "net/ssh"
=> true
jruby-9.1.15.0 :002 > Net::SSH.start('myhost.dev', 'username' password: 'password', verbose: Logger::DEBUG){|ssh| puts ssh.exec!('hostname')}
D, [2018-01-17T14:24:29.633089 #26123] DEBUG -- net.ssh.transport.session[7d0]: establishing connection to myhost.dev:22
D, [2018-01-17T14:24:29.884816 #26123] DEBUG -- net.ssh.transport.session[7d0]: connection established
I, [2018-01-17T14:24:29.888234 #26123] INFO -- net.ssh.transport.server_version[7d2]: negotiating protocol version
D, [2018-01-17T14:24:29.888926 #26123] DEBUG -- net.ssh.transport.server_version[7d2]: local is `SSH-2.0-Ruby/Net::SSH_4.2.0 java'
D, [2018-01-17T14:24:29.952538 #26123] DEBUG -- net.ssh.transport.server_version[7d2]: remote is `SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8'
NotImplementedError: unsupported key type `ecdsa-sha2-nistp256'
from /home/qpi/.rvm/gems/jruby-9.1.15.0#some_gem/gems/net-ssh-4.2.0/lib/net/ssh/buffer.rb:286:in `read_keyblob'
Error was raised from buffer.rb:286:in read_keyblob.
Here the part of code which raising the error
unless defined?(OpenSSL::PKey::EC)
raise NotImplementedError, "unsupported key type `#{type}'"
Ok.. lets check, defined OpenSSL::PKey::EC or not:
jruby-9.1.15.0 :003 > defined?(OpenSSL::PKey::EC) ? 'defined' : 'not defined'
=> "defined"
What am I doing wrong?
When i use ruby (not jruby), everything works fine
Not a real solution but I found a hack that does the trick for me.
https://github.com/jruby/jruby-openssl/issues/105
In short, before your Net::SFTP.start, put these 2 lines.
Net::SSH::Transport::Algorithms::ALGORITHMS.values.each { |algs| algs.reject! { |a| a =~ /^ecd(sa|h)-sha2/ } }
Net::SSH::KnownHosts::SUPPORTED_TYPE.reject! { |t| t =~ /^ecd(sa|h)-sha2/ }
and your problem should be gone.

undefined method unpack for nil:NilClass when rendering JSON

I'm working on a Rails 5 API application and Im having trouble when trying to render json. Take that simple controller:
module Api
module V1
class UsersController < ApplicationController
def sign_up
#user = User.new user_params
if #user.save
render json: {status: :ok, user: #user.to_json }
else
render json: { status: :error, errors: #user.errors }, status: :unprocessable_entity
end
end
end
end
end
When I test this request with a simple spec:
RSpec.describe Api::V1::UsersController, type: :controller do
context 'As an unregistered user' do
context 'signing up with valid params' do
let(:valid_params) do
{ name: 'Test User', email: 'test#test.com', password: '123456789', password_confirmation: '123456789' }
end
it 'returns a 200 status' do
post :sign_up, params: { user: valid_params }
expect(response.status).to eq 200
end
end
end
end
I get an error thrown at me:
Failures:
1) Api::V1::UsersController As an unregistered user signing up with valid status returns a 200 status
Failure/Error: render json: {status: :ok, user: #user.to_json }
NoMethodError:
undefined method `unpack' for nil:NilClass
# ./app/controllers/api/v1/users_controller.rb:10:in `sign_up'
# ./spec/controllers/api/v1/users_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
I'm not using any gems that alter rendering yet so I'm really lost of what might be the problem. Thanks in advance.

rspec routing with subdomain

I'm having a Rails 5 api only app using rspec and versioned this way :
app
- controllers
- api
- v1
- users_controller.rb
My api/v1/users_controller.rb :
module Api::V1
class UsersController < ApiController
My config\routes.rb :
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
constraints subdomain: 'api' do
scope module: 'api' do
namespace :v1 do
resources :users
end
end
end
end
When I check the routes with rails routes it shows me.
Prefix Verb URI Pattern Controller#Action
v1_users GET /v1/users(.:format) api/v1/users#index {:subdomain=>"api"}
POST /v1/users(.:format) api/v1/users#create {:subdomain=>"api"}
v1_user GET /v1/users/:id(.:format) api/v1/users#show {:subdomain=>"api"}
PATCH /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
PUT /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
DELETE /v1/users/:id(.:format) api/v1/users#destroy {:subdomain=>"api"}
My spec file :
require "rails_helper"
RSpec.describe Api::V1::UsersController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/v1/users").to route_to("api/v1/users#index")
end
it "routes to #create" do
expect(:post => "/v1/users").to route_to("api/v1/users#create")
end
it "routes to #show" do
expect(:get => "/v1/users/1").to route_to("api/v1/users#show", :id => "1")
end
it "routes to #update via PUT" do
expect(:put => "/v1/users/1").to route_to("api/v1/users#update", :id => "1")
end
it "routes to #update via PATCH" do
expect(:patch => "/v1/users/1").to route_to("api/v1/users#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/v1/users/1").to route_to("api/v1/users#destroy", :id => "1")
end
end
end
But when I'm testing my routes with rspec it fails as it.
bundle exec rspec spec/routing/users_routing_spec.rb
FFFFF
Failures:
1) Api::V1::UsersController routing routes to #index
Failure/Error: expect(:get => "/v1/users").to route_to("api/v1/users#index")
No route matches "/v1/users"
# ./spec/routing/users_routing_spec.rb:7:in `block (3 levels) in <top (required)>'
I don't understand why. Any idea ?
You have to specify "subdomain" for your spec.
before do
Rails.application.routes.default_url_options[:host] = 'test.host'
end
it "routes to #index" do
expect(:get => v1_users_url).to route_to('v1/users#index', subdomain: 'api')
end

mysql dbi connection: works in irb, not in script?

I am trying to use the rubygem DBI to connect to MYSQL on Windows 7; I can connect using irb but not from within a ruby script, which has stumped me for a few days now...
Here is my gem env output:
RubyGems Environment:
- RUBYGEMS VERSION: 1.8.28
- RUBY VERSION: 1.9.3 (2014-02-24 patchlevel 545) [i386-mingw32]
- INSTALLATION DIRECTORY: C:/Ruby193/lib/ruby/gems/1.9.1
- RUBY EXECUTABLE: C:/Ruby193/bin/ruby.exe
- EXECUTABLE DIRECTORY: C:/Ruby193/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86-mingw32
- GEM PATHS:
- C:/Ruby193/lib/ruby/gems/1.9.1
- C:/Users/rick/.gem/ruby/1.9.1
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- http://rubygems.org/
Here is my irb connection:
irb(main):001:0> require 'dbi'
=> true
irb(main):004:0> dbh=DBI.connect("DBI:Mysql:host=127.0.0.1;port=3306", "rick",>
=> #<DBI::DatabaseHandle:0x2c30bb0 #handle=#<DBI::DBD::Mysql::Database:0x2c30dd8
#handle=#<Mysql:0x2c30f28>, #attr={"AutoCommit"=>true}, #have_transactions=true
, #mutex=#<Mutex:0x2c30bf8>>, #trace_output=nil, #trace_mode=nil, #convert_types
=true, #driver_name="Mysql">
irb(main):005:0> row = dbh.select_one("SELECT VERSION()")
=> ["5.5.25a"]
irb(main):006:0> puts row
5.5.25a
=> nil
irb(main):007:0>
And here is my script:
require 'DBI'
require 'mysql'
# connect to the MySQL server
begin
dbh = DBI.connect("DBI:Mysql:wikifracdb:127.0.0.1;port=3306", "rick", "rick")
# get server version string and display it
row = dbh.select_one("SELECT VERSION()")
puts "Server version: " + row[0]
rescue DBI::DatabaseError => e
puts "An error occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
# disconnect from server
dbh.disconnect if dbh
end
But when I run my script, I get:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:93: warning: already in
itialized constant VERSION
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:96: warning: already in
itialized constant API_VERSION
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:100: warning: already i
nitialized constant DEFAULT_TRACE_MODE
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:101: warning: already i
nitialized constant DEFAULT_TRACE_OUTPUT
An error occurred
Error code: 2003
Error message: Can't connect to MySQL server on 'localhost' (10061)
I have Windows Firewall turned off.
Any suggestions will be much appreciated...this has been driving me crazy!

vagrant : chef_solo | how i can change log path from mysql server and mongodb?

I'm working with vagrant and chef .
As far as everything goes , only when I use the Logpath of mysql and mongodb change in the vagrant file , I get an error.
if anyone here has a tip and can help me would be happy.
In Vagrantfile I have stated so ...
:mysql => {
:server_root_password => 'password',
:server_debian_password => 'password',
:server_repl_password => 'password',
:allow_remote_root => true,
:log_dir => "/vagrant/www/logs/mysql",
:tunable => {
:log_slow_queries => "/vagrant/www/logs/mysql/slow.log",
:log_error => true,
:log_warnings => true
}
},
:mongodb => {
:logpath => "/vagrant/www/logs/mongodb"
},
================================================================================
Error executing action `create` on resource 'directory[/vagrant/www/logs/mysql]'
================================================================================
Errno::EPERM
------------
Operation not permitted - /vagrant/www/logs/mysql
Resource Declaration:
---------------------
# In /tmp/vagrant-chef/chef-solo-1/cookbooks/mysql/recipes/server.rb
117: directory path do
118: owner 'mysql' unless platform?('windows')
119: group 'mysql' unless platform?('windows')
120: action :create
121: recursive true
122: end
123: end
Compiled Resource:
------------------
# Declared in /tmp/vagrant-chef/chef-solo-1/cookbooks/mysql/recipes/server.rb:117:in `block in from_file'
directory("/vagrant/www/logs/mysql") do
provider Chef::Provider::Directory
action [:create]
retries 0
retry_delay 2
path "/vagrant/www/logs/mysql"
recursive true
cookbook_name :mysql
recipe_name "server"
owner "mysql"
group "mysql"
mode 493
end
[2013-10-31T01:03:09-07:00] DEBUG: Re-raising exception: Errno::EPERM - directory[/vagrant/www/logs/mysql] (mysql::server line 117) had an error: Errno::EPERM: Operation not permitted - /vagrant/www/logs/mysql
This line is the key problem: Operation not permitted - /vagrant/www/logs/mysql
which means it does not allow user to create directory under this path. Please check if user mysql is privileged to access directory /vagrant/www/logs. Maybe you need +x on /vagrant
First, I would not advise using this -- slow log writes will slow down most databases and I wouldn't want to do that to myself.
Anyhow, permissions on vagrant shared folders can be a bit tricky -- in some, if not many, cases you need to set owner / permission from the vagrantfile. This is a bit tricky for /vagrant but you could map another folder if you really don't want to vagrant ssh into the server to read the logs. To do so:
config.vm.synced_folder "logs", "/logs", :mount_options => ['dmode=777', 'fmode=777']
777 is probably overkill but you get the idea.