Reputation: 539
I try to write business logic of my application. It is all ruby classes. There is no database or no UI framework like Rails, Sinatra. I only have a Gem_file on business logic and, Gem_file only contain "mini_test" gem. I use mini_test for testing business logic. Now, I need to add a database to the system. How can I do this? mongoid configuration is made in application.file on Rails. But ,I don't use Rails or any other framework. Is there anyway to make configuration of mongoid without framework like Rails, Sinatra. I hope I can explain my problem. Also, I add my codes in below:
this is my context-
class HeadTeacherDefineAcademicYearContext
attr_reader :person, :academicyear
def initialize(person, academicyear)
@person, @academicyear = person, academicyear
@person.extend HeadTeacher
end
def call
@person.define_academic_year @academicyear
end
end
this is my role module
module HeadTeacher
def define_academic_year(academicyear)
#i write db save process here using any database
end
end
my model class
class AcademicYear
attr_accessor :year
end
Upvotes: 2
Views: 439
Reputation: 1159
Add gem "mongoid", "~> 3.0.0"
to your Gemfile
Then put configuration yaml file to your project with contents like this:
development:
sessions:
default:
database: mongoid
hosts:
- localhost:27017
Then use Mongoid.load!("path/to/your/mongoid.yml", :development)
in your app.
In every class you want to save objects to DB you have to include Mongoid::Document
.
So your example becomes:
class HeadTeacherDefineAcademicYearContext
attr_reader :person, :academicyear
field :person, type: String
field :academicyear, type: Date
...
end
You should better check mongoid docs for stuff to do next.
Upvotes: 0
Reputation:
You have to include gem 'mongoid'
in your Gemfile and install it. After that, you can require and initialize Mongoid where you need it:
require 'mongoid'
Mongoid.load!("mongoid.yml", :development)
It expects a mongoid.yml
file with configuration. Examlpe:
development:
sessions:
default:
database: myapp_development
hosts:
- localhost:27017
Of course, you can use another context than :development
, maybe assign it via a environment variable. Now, add Mongoid::Document
to your model:
class AcademicYear
include Mongoid::Document
field :year, type: Integer
end
Upvotes: 1