mongoid configuration on ruby without framework - ruby

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

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

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.

Related

Store gem configuration in the gem's module

My gem exposes a module that can be included on Mongoid mapper classes to keep track of changes.
I want the user to be able to flag specific fields on their classes so that they will be handled differrently.
My idea is to create an appendable flag. Please see an outline of the relevant sections of the module below:
module PendingChanges
included do
attr_accessor :__appendable_fields
private def self.appendable(field)
self.__appendable_fields << field
end
end
end
So when the user want to flag a field on his document as "appendable" they would do something like:
class Person
include PendingChanges
field :name, type: String
field :emails, type: Array
appendable :emails <- this is what they would do
end
I don't seem to be able to make it work, as __appendable_fields is always nil. Also, I'm not confident this is the "Ruby way" of approaching this?
Apparently, I had to use mattr_accessor instead.
I'm able to access it then with self.__appendable_fields on the appendable method.

How to set customized pretty URLs in Rails?

I want to show pretty URLs for my posts like year/month/title and don't want to show the id or controller name.
How can I do this in Ruby on Rails?
You should check out the friendly_id gem which lets you set another attribute than id to resolve models into URLs and vice versa.
Using this gem to generate user URLs by nick:
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
end
User.create! name: "Joe Schmoe"
GET http://localhost:3000/users/joe-schmoe

Ruby Gem with Acroynym in the name

[SOLVED: See my comment below]
I've created a Ruby Gem to connect to my application's API: my_app_api. I'd like to use it like so: MyAppAPI::Foo.bar(). However, I get:
NameError: uninitialized constant MyAppAPI
I know the standard way to call/name this would be MyAppApi::Foo.bar(), but I'd prefer to keep with acronym class naming conventions. How do I specify/load the module?
For reference, the class looks like this:
module MyAppAPI
class Foo < ActiveResource::Base
extend MyAppAPI
self.site = 'http://localhost:3000/api/'
self.format = :json
class << self
def bar
return 'huzzah!'
end
end
end
end
And the my_app_api.rb file looks like this:
require "rubygems"
require 'active_resource'
require 'my_app_api/foo'
Have you tried loading the gem the normal way?
require 'my_app_api'
MyAppAPI::Foo.bar()
The constant name MyAppAPI is fine and is not the cause of the problem. There are tons of Ruby core classes/modules that have acronyms in their names:
http://www.ruby-doc.org/core-1.9.3/GC.html
http://www.ruby-doc.org/core-1.9.3/RubyVM.html
http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html
Try declaring the empty module in my_app_api.rb after your require statements:
module MyAppAPI
end
This may help if you're relying on a dynamic class and module loading mechanism (like Rails uses).
I assume your app is explicitly calling require "my_app_api". What kind of app is this, and where are you doing the require?

getting all the Active Record models in app/models directory

I'm planning to create a ruby gem which requires to get all the ActiveRecord models from the directory (typically)
RAILS_ROOT/app/models
how can I get the list of model names (physical) in ruby (ruby 1.9)
cheers
sameera
So, if the class name matches with the file name, you can use something like this:
# models/user.rb
class User < ActiveRecord::Base
end
Dir.glob("./models/*.rb").each {|model| require model}
user = User.new
ActiveRecord::Base.subclasses.collect(&:name)
Returns all the model name.

How do you use ActiveRecord3's associations feature outside of Rails?

I am working on a script to translate an old Rails 2 application database into a new Rails 3 application. The new application is a rewrite and simplification of the database schema.
I have created a stand-alone ruby program independent of Rails to do the heavy lifting and am leveraging the adapter pattern with Ruby modules to manipulate two database connections and move the data from one system to the other.
I have successfully implemented ActiveRecord (using include "active_record") in my translator models and all my find and validations are working as expected. However, the associations are resulting in method_missing calls.
Do I need to do something special to allow the associations to work outside of the Rails environment? I'm hoping for a simple answer like "you forgot to require this key file".
Here is a minimal example using activerecord without rails:
require 'active_record'
class Site < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :site
end
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:database => 'test',
:user => 'root'
)
s = Site.first
p s
p s.users
p s.users[0].site
There is really no more than this !
The gem used here is activerecord 3 but the exact same example works with activerecord 2.
PS: obviously you need a test database with a sites and users tables to run this test.

Resources