Im trying to store my api key in a yaml file
fresh_desk.yml
production:
:api_key: 12345
staging:
:api_key: 12345
development:
:api_key: my api key here
then in my lib folder i have a file called
fresh_desk_api_wrapper.rb
class FreshDeskApiWrapper
attr_accessor :config, :client
def initialize
self.config = YAML.load("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new("http://onehouse.freshdesk.com/", config.api_key, "X")
end
def post_tickets(params)
client.post_tickets(params)
end
end
then in my
clients_controller.rb
def create
FreshDeskApiWrapper.new().post_tickets(params[:client])
redirect_to new_client_path
end
but when i submit my form i get an error
undefined method `api_key' for nil:NilClass
does anyone know whats causing this? and how to fix it?
you might need a File.open
blah.yml
production:
:api_key: 12345
staging:
:api_key: 45678
development:
:api_key: 10203
Then you can load it into a hash
>> require 'yaml'
=> true
>> config = YAML::load(File.open('blah.yml'))
=> {"production"=>{:api_key=>12345}, "staging"=>{:api_key=>45678}, "development"=>{:api_key=>10203}}
Related
I want to populate my .yml file in config folder dynamically when my server is loading.
The following is an example of my .yml file
# Configuration Credentials
development: &development
user: "***"
password: "***"
test:
<<: *development
non-prod:
user: "***"
password: "***"
production: &production
user: "***"
password: "***"
I want to set the value for each key in the form of embedded ruby like this:
development: &development
user: <%= get_value_for(user) %>
password: <%= get_value_for(password) %>
I want to load the .yml file when the server is about to run.
I want to know where should I define the get_value_for method so I can call it inside my yml file? (probably in application.rb but I do not know how exactly)
Create a custom class and define the method their. Then require the class inside config/application.rb
# app/global/database_details.rb
class DatabaseDetails
def self.get_value_for(user)
end
end
Inside config/application.rb
require_relative '../app/global/database_details'
module AppName
class Application < Rails::Application
end
end
Inside config/database.yml
development: &development
user: <%= DatabaseDetails.get_value_for(user) %>
password: <%= DatabaseDetails.get_value_for(password) %>
I am trying to setup Recaptcha in my rails 5 application as it's described in the documentation but it fails.
I use this gem: recaptcha (4.6.6), ruby 2.5.0 and rails 5.1.4
In view form:
<%= flash[:recaptcha_error] %>
<%= recaptcha_tags %>
In devise registrations controller:
prepend_before_action :check_captcha, only: :create
private
def check_captcha
unless verify_recaptcha
self.resource = resource_class.new sign_up_params
resource.validate # Look for any other validation errors besides Recaptcha
respond_with_navigational(resource) { redirect_to new_user_registration_path }
end
end
In my initializers/recaptcha.rb
Recaptcha.configure do |config|
config.site_key = Rails.application.config_for(:recaptcha)['site_key']
config.secret_key = Rails.application.config_for(:recaptcha)['secret_key']
end
In my recaptcha.yml:
default: &default
site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>
development:
<<: *default
test:
<<: *default
staging:
<<: *default
production:
<<: *default
In /etc/environments:
# RECAPTCHA
RECAPTCHA_SITE_KEY=6Lfg3ksUAAAAABOD_OXCtPO60*******
RECAPTCHA_SECRET_KEY=6Lfg3ksUAAAAAOmFGdAxdo8*******
PROBLEM
After adding ENV variables to /etc/environments, I exported it with this command:
for line in $( cat /etc/environment ) ; do export $line ; done
Then I check that Recaptcha module is configured correctly:
/home/deploy/apps/app_name/current$ bundle exec rails c
Loading staging environment (Rails 5.1.4)
2.5.0 :001 > Recaptcha::Configuration.new
=> #<Recaptcha::Configuration:0x0000000006601908 #skip_verify_env=["test", "cucumber"], #handle_timeouts_gracefully=true, #secret_key="6Lfg3ksUAAAAAOmFGdAxdo8H*************", #site_key="6Lfg3ksUAAAAABOD_OXCtPO*************">
2.5.0 :002 > Recaptcha::Configuration.new.site_key!
=> "6Lfg3ksUAAAAABOD_OXCtPO*************"
Also, I see these ENV variables when I run printenv command (so it's really loaded)
After that, I restarted rails and got an error
No site key specified.
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/configuration.rb:47:in `site_key!'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:79:in `recaptcha_components'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:15:in `recaptcha_tags'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:27:in `block in _app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `block in capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:203:in `with_output_buffer'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/form_helper.rb:450:in `form_for'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:21:in `_app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/template.rb:157:in `block in render'
I am posting here in case someone is looking for a Rails 5.2 solution to setting up Recaptcha keys. This solution utilizes the new config/master.key and config/credentials.yml.enc encryption file.
Add the Recaptcha keys to the credentials.yml.enc file by editing the file in your local terminal:
EDITOR="vim" rails credentials:edit
After adding the keys to the credentials file (see example below), save and exit the file. Upon exit, the credentials.yml.enc file will then be automatically encrypted. The master.key is necessary for decryption by your application. Before encryption:
recaptcha_site_key: 6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy
recaptcha_secret_key: 6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxx
3. Create a file named config/recaptcha.rb in your Rails application and add the following code to it:
Recaptcha.configure do |config|
config.site_key = Rails.application.credentials.dig(:recaptcha_site_key)
config.secret_key = Rails.application.credentials.dig(:recaptcha_secret_key)
end
This solution works locally and on Ubuntu/nginx in production. You won't need a gem or environment variables for it to work. If the master.key fails to decrypt, you may need to delete both the credentials.yml.enc file and possibly even the master.key file, then repeat this process locally (EDITOR="vim" rails credentials:edit, etc.) before copying over a new master.key to production and re-deploying.
I still don't know what is the cause of the "No site key specified" error.
I really don't like gem 'recapthca' works directly with ENV variables,
and also I spent too much time on investigations.
So, I decided to not use this gem and write my own code.
I use only Invisible Recaptcha in my application.
Config file (loads secret and site keys)
# /config/recaptcha.yml
default: &default
site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>
development:
<<: *default
test:
<<: *default
staging:
<<: *default
production:
<<: *default
Application helper (a button with Recaptcha helper)
# /app/helpers/application_helper.rb
module ApplicationHelper
def submit_with_recaptcha(text, custom_options)
unless custom_options[:data].has_key?(:form_id)
raise "Data Form Id option not found ('{data: {form_id: 'id_without_dash'}')."
end
options = {
type: 'button',
data: {
form_id: custom_options[:data][:form_id],
sitekey: recaptcha_site_key,
callback: "submit#{custom_options[:data][:form_id].camelize}#{Time.current.to_i}"
},
class: (custom_options[:class].split(' ') + ['g-recaptcha']).uniq.join(' ')
}
script_code = <<-SCRIPT
function #{options[:data][:callback]}() {
document.getElementById('#{options[:data][:form_id]}').submit();
}
SCRIPT
javascript_tag(script_code) + content_tag(:div, class: 'recaptcha_wrapper'){ submit_tag(text, options) }
end
private
def recaptcha_site_key
Rails.application.config_for(:recaptcha)['site_key']
end
end
Verification service (as it uses external API)
# app/services/google_recaptcha/verification.rb
module GoogleRecaptcha
# https://developers.google.com/recaptcha/docs/verify
class Verification
# response - params['g-recaptcha-response'])
def self.successful?(recaptcha_params, remoteip)
verify_url = URI.parse('https://www.google.com/recaptcha/api/siteverify')
verify_request = Net::HTTP::Post.new(verify_url.path)
verify_request.set_form_data(
response: recaptcha_params,
secret: secret_key,
remoteip: remoteip
)
connection = Net::HTTP.new(verify_url.host, verify_url.port)
connection.use_ssl = true
Rails.logger.info '[RECAPTCHA] Sending verification request.'
verify_response = connection.start { |http| http.request(verify_request) }
response_data = JSON.parse(verify_response.body)
Rails.logger.info "[RECAPTCHA] Verification response is#{' not' unless response_data['success']} successful."
response_data['success']
end
private
def self.secret_key
Rails.application.config_for(:recaptcha)['secret_key']
end
end
end
Controller Concern (Recaptcha verification in before_action)
# app/controllers/concerns/recaptchable.rb
module Recaptchable
extend ActiveSupport::Concern
included do
before_action :verify_recaptcha, only: [:create]
end
private
def verify_recaptcha
unless GoogleRecaptcha::Verification.successful?(recaptcha_params['g-recaptcha-response'], request.remote_ip)
render :new
return
end
end
def recaptcha_params
params.permit(:'g-recaptcha-response')
end
end
Usage
Add concern to your controller:
class MyController < ShopController
include Recaptchable
end
Add www.google.com/recaptcha/api.js javascript to your page
Add submit_with_recaptcha helper into your form
<%= form_for #delivery, url: users_delivery_path, method: 'post' do |f| %>
<%= submit_with_recaptcha t('order.deliver.to_confirmation'), data: {form_id: 'new_delivery'}, class: 'btn-round' %>
<% end %>
<%= javascript_include_tag "https://www.google.com/recaptcha/api.js?hl=#{I18n.locale}", 'data-turbolinks-track': 'reload' %>
That's it.
Note: I'm posting this answer here for people who may find this question. Here is how I solved the problem.
I use local_env.yml for my environment variables. I just started using the gem and added RECAPTCHA_SITE_KEY & RECAPTCHA_SECRET_KEY to local_env.yml. I got the same error.
It took a bit to figure out that the gem directly used the variables. I ended up putting the following statements in ~/.bashrc similar to what the documentation said but without the quotes around the values.
export RECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy
export RECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx
I host my applications on Heroku. I executed the following terminal commands to set my environment variables in Heroku.
heroku config:set RECAPTCHA_SITE_KEY=‘6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy’
heroku config:set RECAPTCHA_SECRET_KEY=‘6LcGuI4U6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxxAAAAGAWMYRKFGfHUCSD0SPrMX2lfyl9’
Are you using nginx? Nginx removes ENV vars (except TZ) and it seems that the recaptcha gem is particularly sensitive to this. From experience, when using the dotenv gem other ENV vars work ok, recaptcha ENV vars are ignored.
You can solve the issue by adding the env vars to the top of your nginx.conf.
env RECAPTCHA_SITE_KEY=value1;
env RECAPTCHA_SECRET_KEY=value2;
Here's nginx's documentation on the matter.
Here is my database.yml config:
development:
adapter: ibm_db
username: "username"
password: "password"
database: '*LOCAL'
schema: <%= ENV['CA_SCHEMA'] %>
ibm_i_isolation: 'none'
Here is my initializer:
module Ca2eModelExtractor
class Application < Rails::Application
config.before_configuration do
ENV['CA_SCHEMA']= 'XAMDL'
end
end
end
After running rails c I did ENV['CA_SCHEMA'] and saw XAMDL as an output, so it works as expected. But when I run ActiveRecord::Base.configurations, I got a hash, where schema is nil. Any ideas?
In a rails application, I have this code in pure ruby :
class LinkCreator
attr_accessor :animal
def initialize(animal:)
#animal = animal
end
def call
"something#{link_id}"
end
private
def link_id
connection.execute(sql_request).first.first
end
def sql_request
"SELECT field FROM table WHERE field_id = '#{field_id}' LIMIT 1"
end
def field_id
animal.field_id
end
def connection
ActiveRecord::Base.establish_connection(
adapter: "mysql",
host: ENV["MYSQL_HOST"],
username: ENV["MYSQL_USERNAME"],
password: ENV["MYSQL_PASSWORD"],
database: ENV["MYSQL_DB_NAME"]
).connection
end
end
As you can see, this is not a model but only a simple class. The problem is than the connection of activerecord is changed and the other requests, later, are executed on the new connection.
Is it possible to establish a connection only in a block and go back to the old connection. I know I can establish another connection but this is very bad for performance.
It would be nice if you keep all database connections in database.yml
development:
adapter: mysql2
other stuff...
db_2:
adapter: mysql2
other stuff..
other_envs:
.....
Then create a class
class OtherDB < ActiveRecord::Base
establish_connection(:db_2)
end
From your controller you can access just like
OtherDB.table_name = "table_name"
OtherDB.first
Check my blog here http://imnithin.github.io/multiple-database.html
Have found most short example in Rails codebase at activerecord/test/support/connection_helper.rb and slightly adapted:
def with_another_db(another_db_config)
original_connection = ActiveRecord::Base.remove_connection
ActiveRecord::Base.establish_connection(another_db_config)
yield
ensure
ActiveRecord::Base.establish_connection(original_connection)
end
Usage (given that you have another_db: section in your database.yml):
with_another_db(ActiveRecord::Base.configurations['another_db']) do
ActiveRecord::Base.connection.execute("SELECT 'Look ma, I have changed DB!';")
end
You can perform some queries within a block. First, define some module which will extend ActiveRecord, as below. This is a part of code used in production to change db connection per each request as well as to temporarily switch db to perform some queries within another database.
# RAILS_ROOT/lib/connection_switch.rb
module ConnectionSwitch
def with_db(connection_spec_name)
current_conf = ActiveRecord::Base.connection_config
begin
ActiveRecord::Base.establish_connection(db_configurations[connection_spec_name]).tap do
Rails.logger.debug "\e[1;35m [ActiveRecord::Base switched database] \e[0m #{ActiveRecord::Base.connection.current_database}"
end if database_changed?(connection_spec_name)
yield
ensure
ActiveRecord::Base.establish_connection(current_conf).tap do
Rails.logger.debug "\e[1;35m [ActiveRecord::Base switched database] \e[0m #{ActiveRecord::Base.connection.current_database}"
end if database_changed?(connection_spec_name, current_conf)
end
end
private
def database_changed?(connection_spec_name, current_conf = nil)
current_conf = ActiveRecord::Base.connection_config unless current_conf
current_conf[:database] != db_configurations[connection_spec_name].try(:[], :database)
end
def db_configurations
#db_config ||= begin
file_name = "#{Rails.root}/config/database.yml"
if File.exists?(file_name) || File.symlink?(file_name)
config ||= HashWithIndifferentAccess.new(YAML.load(ERB.new(File.read(file_name)).result))
else
config ||= HashWithIndifferentAccess.new
end
config
end
end
end
ActiveRecord.send :extend, ConnectionSwitch
Now you can use it as below:
ActiveRecord.with_db("db_connection_name") do
# some queries to another db
end
If you want to connect to postgres sql, you can use pg ruby gem & add the below code inside the block.
postgres = PG.connect :host => <host_name>, :port => <port>, :dbname => <database_name>, :user => <user>, :password => <password>
tables = postgres.exec(query)
tables.num_tuples.times do |i|
print tables[i]
end
To connect to mysql db inside a block, use mysql2 ruby gem & add the below code inside the block.
db = Mysql2::Client.new ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(<database_url>).to_hash
data = db.query(<<-SQL)
select * from students
SQL
print data
I use environment variables taken from Heroku's DATABASE_URL to connect to different databases:
class Database
def self.development!
ActiveRecord::Base.establish_connection(:development)
end
def self.production!
ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])
end
def self.staging!
ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])
end
end
e.g.:
Database.production!; puts User.all.map(&:name)
Database.staging!; puts User.all.map(&:name)
It might help to use an instance variable to store the connection. Something like this:
def connection
#connection ||= ActiveRecord::Base.establish_connection(
adapter: "mysql",
host: ENV["MYSQL_HOST"],
username: ENV["MYSQL_USERNAME"],
password: ENV["MYSQL_PASSWORD"],
database: ENV["MYSQL_DB_NAME"]
).connection
end
That way the existing connection is retrieved on future connection attempts, rather than establishing a new one.
Try active_record_slave gem:
Ruby gem: active_record_slave
Using APP_CONFIG to store values for system-wide access, works great but not for ActionMailer email views. Does anyone knows how to fix this?
In load_config.rb (config folder) i load it like:
APP_CONFIG = YAML.load_file("#{Rails.root}/config/application.yml")[Rails.env]
Then in my Mailer views (HAML) I try to use them like regularly in my application like:
Welcome to our application named:
= APP_CONFIG['app_name']
How would i get access to all my APP_CONFIG values inside action mailer views?
Try to something like this:
app/controllers/user_controller.rb
def some_method
app_name = APP_CONFIG['app_name']
UserMailer.welcome_mail(app_name).deliver
end
app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
default :from => "info#mypage.com"
def welcome_mail(app_name)
#app_name = app_name
mail(:to => "test#mypage.com", :subject => "[system] User Welcome!")
end
end
app/views/user_mailer/welcome_mail.html.haml
%p Welcome to our application named:
=#app_name
I think it should work.
I fixed it like this:
default: &default
app_name: "My APP"
app_mail: "info#..."
development:
<<: *default
...
production:
<<: *default
...
The problem was it was using the RAILS_ENV and I had not merged the default section into the production and development mode, like this its clean and you can just do APP_CONFIG["any_var"] having the default (global) ones to store google analytics etc and the ENV specific ones under development and production :)