Configuring Neo4j with rails for different environments - ruby-on-rails

I have configured Neo4j in development environment using neo4j core gem.
To create a new connection, i have used the below code in application.rb
Application.rb
neo4j_adaptor = Neo4j::Core::CypherSession::Adaptors::HTTP.new('http://localhost:7474')
neo4j_session = Neo4j::Core::CypherSession.new(neo4j_adaptor)
How to configure the neo4j so that development environment and test environment uses different database.
eg: for development sample_development and for running rspec sample_test.

I don't know how much experience you have with Rails. But in rails you mainly have 3 environments be default:
1- development
2- test
3- production
You can have different configs for different environments as shown in this SO question:
Best way to create custom config options for my Rails app?
Last thing, I would not recommend to use the Neo4j adapter directly unless you are really experienced and need direct access to it because of business requirements.
I'd recommend to use Neo4jrb wrapper around the core adapter as shown here:
https://neo4jrb.readthedocs.io/en/9.2.x/Setup.html#generating-a-new-app
UPDATE
Create a file called neo4j.yml inside config directory in your project with following code:
development:
neo4j_api: http://localhost:7474
test:
neo4j_api: http://something_else:7474
production:
neo4j_api: http://maybe_something_else:7474
then create an initializer in your project lets call it neo4j.rb so its path should be: config/initializers/neo4j.rb.
Inside this initializer put the following code:
NEO4J_CONFIG = YAML.load_file(Rails.root.join('config/neo4j.yml'))[Rails.env]
Then you will have the NEO4J_CONFIG accessible at any part of your rails application like:
NEO4J_CONFIG['neo4j_api']
and your code should look like:
neo4j_adaptor = Neo4j::Core::CypherSession::Adaptors::HTTP.new(NEO4J_CONFIG['neo4j_api'])
neo4j_session = Neo4j::Core::CypherSession.new(neo4j_adaptor)

Related

Scope of Models(?) in Rails

I'm new to Ruby on Rails and am trying to access my site's database. I generated and set up a model and controller called Machine, and noticed that in places like the Machine view I could iterate through all the machines in my database simply using #machines.each. However, this doesn't appear to be universal, as when I created a new Ruby file directly in my project's outermost directory, both #machines.each and the attempted assignment #machines = Machine.all threw errors (a NoMethodError and NameError respectively). Here's an example of code I could try to run:
#machines = Machine.all
#machines.each do |machine|
puts machine.created_at
end
Perhaps I need some kind of import statement?
If you are writing a script in plain Ruby -- then yes, you'll have to import everything manually, establish a connection to the DB, etc.
The code would roughly look like this:
require 'active_support'
require 'active_record'
your_db_config = {
# your DB config goes here
}
ActiveSupport::Dependencies.autoload_paths += File.join(__dir__, "app/models")
ActiveRecord::Base.establish_connection(your_db_config)
machines = Machine.all
Consider creating a task if you want Rails to take care of all that and don't want to be doing all that stuff manually.
When you start a rails server (or a rails console) it preloads your Rails application so that your models, constants, etc. are automatically in scope. If you want to access your application's resources from a separate script you still need to load the app. The simplest way to do that is with the rails runner command, which loads your app and then executes a script. So if your script above is in lib/show_machines you'd run:
$ bin/rails runner lib/show_machines
If you like self-executing scripts you can also use runner as a 'shebang' line:
#!/usr/bin/env <your_project_path>/rails/runner
#machines = Machine.all
#machines.each do |machine|
puts machine.created_at
end

How to setup basic ManageIQ automate environment in Rails console?

I used to run some operations in ManageIQ through automate simulation, which is available from UI.
I'd like to find a way to reproduce these operations from rails console.
For example operations for Instance management - migrate, evacuate or relocate instance.
How do I make it?
There's the common way to do this:
Set up a basic $evm context in a Rails console
# rails c
# $evm = MiqAeMethodService::MiqAeService.new(MiqAeEngine::MiqAeWorkspaceRuntime.new)
For example you can find any VM in vmdb and define it into a variable:
# vm = $evm.vmdb('vm').find('some_id')
Similar with other objects, e.g.
flavor = $evm.vmdb('flavor').find(flavor_id)

When using ActiveRecord::Database::Tasks outside of Rails, what do I need to configure to avoid a development database not configured error?

I'm calling ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, file) in a Ruby file script (essentially it's a Thor task) in a Ruby off Rails app and I get the following error:
/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:248:in `resolve_symbol_connection': 'development' database is not configured. Available: [] (ActiveRecord::AdapterNotSpecified)
Does ActiveRecord::Tasks::DatabaseTasks give me the functions I need to set up a default database configuration outside of rails (I'm assuming I need to provide info similar to what's in database.yml in Rails)? If so, what are the functions I would need to call? I'm looking at http://api.rubyonrails.org/classes/ActiveRecord/Tasks/DatabaseTasks.html but it's a bit unclear to me.
Before load the schema, you need to load the database configuration (like the database.yml):
DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
I was able to get this to work in a non-Rails project with the following...
db_config = YAML.load_file('path/to/database.yml')
ActiveRecord::Tasks::DatabaseTasks.load_schema_for(
db_config, :ruby, 'path/to/schema.rb')

Accessing a database through Rails model from a seperate Ruby script

I have a Rails application with a database (PostgreSQL using ActiveRecord)
In a separate directory on the same server I have a Ruby script.
How can I, from the Ruby script, reach the Rails database through one of my Rails models?
I have seen that it is possible to require ActiveRecord and pass in the database details, but from what I understand I would need to rebuild the model, which means a lot of repetition of validations, methods, etc. Instead I'd like to somehow use the model that's already in place.
I found a solution that has the behaviour I was looking for, and am posting it as an answer for anyone who comes across this question at a later date.
Setting ENV['RAILS_ENV'] = "production" and then simply requiring the environment.rb file (with the appropriate path) in the Ruby script solves the issue very nicely.
This is similar to the answer provided by #MurifoX, but saves you having to re-declare the DB connection.
Try using rails runner. According to: http://guides.rubyonrails.org/command_line.html#rails-runner
runner runs Ruby code in the context of Rails non-interactively. For
instance:
bin/rails runner "Model.long_running_method"
In my experience this works nicely to run scripts that rely on Active Record and more.
Add the -e switch to the command to force the use of your production database connection:
bin/rails runner -e staging "Model.long_running_method"
Add any other environment variables that may be required to complete the database connection. If you use the Devise gem, you will also need to pass in a secret to allow the Devise initializations to complete. Other gems may equally need some assistance to get started.
You can use require to pass the relative path to your model, and then instatiate it a use.
require '/path/to/your/model/inside/your/app'
model = Model.new
For the connection, if you are using postgresql, you can use the PGconn class from the pg gem like this:
#connection = PGconn.open(
:user => 'postgres',
:password => 'password',
:host => 'host',
:dbname => 'dbname')

Ruby on rails with multiple production settings

How can we run a ruby on rails application with different database configuration?
in detail: I want to run multiple instance of a rails app with different database config for each on production. How is it possible?
I think you can duplicate the config in database.yml into different environments, like prod1, prod2 ... and then set RAILS_ENV environment variable to match before starting up each respective server...
You can duplicate your database.yml file as DGM mentioned. However, the right way to do this would be to use a configuration management solution like Chef.
If you look at the guide for setting up Rails stack, it includes a 2 front-end Web server + 1 back-end DB server. Which would include your case of duplicating database.yml file.
If you are able to control and configure each Rails instance, and you can afford wasting resources because of them being on standby, save yourself some trouble and just change the database.yml to modify the database connection used on every instance. If you are concerned about performance this approach won't cut it.
For models bound to a single unique table on only one database you can call establish_connection inside the model:
establish_connection "database_name_#{RAILS_ENV}"
As described here: http://apidock.com/rails/ActiveRecord/Base/establish_connection/class
You will have some models using tables from one database and other different models using tables from other databases.
If you have identical tables, common on different databases, and shared by a single model, ActiveRecord won't help you. Back in 2009 I required this on a project I was working on, using Rails 2.3.8. I had a database for each customer, and I named the databases with their IDs. So I created a method to change the connection inside ApplicationController:
def change_database database_id = params[:company_id]
return if database_id.blank?
configuration = ActiveRecord::Base.connection.instance_eval { #config }.clone
configuration[:database] = "database_name_#{database_id}_#{RAILS_ENV}"
MultipleDatabaseModel.establish_connection configuration
end
And added that method as a *before_filter* to all controllers:
before_filter :change_database
So for each action of each controller, when params[:company_id] is defined and set, it will change the database to the correct one.
To handle migrations I extended ActiveRecord::Migration, with a method that looks for all the customers and iterates a block with each ID:
class ActiveRecord::Migration
def self.using_databases *args
configuration = ActiveRecord::Base.connection.instance_eval { #config }
former_database = configuration[:database]
companies = args.blank? ? Company.all : Company.find(args)
companies.each do |company|
configuration[:database] = "database_name_#{company[:id]}_#{RAILS_ENV}"
ActiveRecord::Base.establish_connection configuration
yield self
end
configuration[:database] = former_database
ActiveRecord::Base.establish_connection configuration
end
end
Note that by doing this, it would be impossible for you to make queries within the same action from two different databases. You can call *change_database* again but it will get nasty when you try using methods that execute queries, from the objects no longer linked to the correct database. Also, it is obvious you won't be able to join tables that belong to different databases.
To handle this properly, ActiveRecord should be considerably extended. There should be a plugin by now to help you with this issue. A quick research gave me this one:
DB-Charmer: http://kovyrin.github.com/db-charmer/
I'm willing to try it. Let me know what works for you.
Well. We have to create multiple environments in you application
create config/environmenmts/production1.rb which will be same as of config/environmenmts/production.rb
then edit database.yml for production1 settings and you are done.
start server using rails s -e production1

Resources