repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/business.rb | spec/models/business.rb | class Business
include Mongoid::Document
set_database :secondary
field :name
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/namespacing.rb | spec/models/namespacing.rb | module Medical
class Patient
include Mongoid::Document
field :name
embeds_many :prescriptions, :class_name => "Medical::Prescription"
end
class Prescription
include Mongoid::Document
field :name
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/page.rb | spec/models/page.rb | class Page
include Mongoid::Document
embedded_in :quiz
embeds_many :page_questions
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/pet.rb | spec/models/pet.rb | class Pet
include Mongoid::Document
field :name
field :weight, :type => Float, :default => 0.0
embeds_many :vet_visits
embedded_in :pet_owner
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/pet_owner.rb | spec/models/pet_owner.rb | class PetOwner
include Mongoid::Document
field :title
embeds_one :pet
embeds_one :address, :as => :addressable
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/description.rb | spec/models/description.rb | class Description
include Mongoid::Document
field :details
referenced_in :user
referenced_in :updater, :class_name => 'User'
validates :user, :associated => true
validates :details, :presence => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/division.rb | spec/models/division.rb | class Division
include Mongoid::Document
field :name, :type => String
embedded_in :league
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/birthday.rb | spec/models/birthday.rb | class Birthday
include Mongoid::Document
field :title
field :date, :type => Date
embedded_in :owner, :inverse_of => :birthdays
def self.each_day(start_date, end_date)
groups = only(:date).asc(:date).where(:date.gte => start_date, :date.lte => end_date).group
groups.each do |date, group|
yield(date, group)
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/league.rb | spec/models/league.rb | class League
include Mongoid::Document
embeds_many :divisions
accepts_nested_attributes_for :divisions, :allow_destroy => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/owner.rb | spec/models/owner.rb | class Owner
include Mongoid::Document
field :name
references_many :events
embeds_many :birthdays
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/animal.rb | spec/models/animal.rb | class Animal
include Mongoid::Document
field :name
field :tags, :type => Array
key :name
embedded_in :person
embedded_in :circus
validates_format_of :name, :without => /\$\$\$/
accepts_nested_attributes_for :person
def tag_list
tags.join(", ")
end
def tag_list=(_tag_list)
self.tags = _tag_list.split(",").map(&:strip)
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/category.rb | spec/models/category.rb | class RootCategory
include Mongoid::Document
embeds_many :categories
end
class Category
include Mongoid::Document
embedded_in :root_category
embedded_in :category
embeds_many :categories
field :name
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/parents.rb | spec/models/parents.rb | class ParentDoc
include Mongoid::Document
embeds_many :child_docs
field :statistic
field :children_order, :type => Array, :default => [] # hold all the children's id
end
class ChildDoc
include Mongoid::Document
embedded_in :parent_doc
attr_writer :position
after_save :update_position
def position
exsited_position = parent_doc.children_order.index(id)
exsited_position ? exsited_position + 1 : parent_doc.aspects.size
end
def update_position
if @position && (@position.to_i > 0)
parent_doc.children_order.delete(id)
parent_doc.children_order.insert(@position.to_i - 1, id)
parent_doc.save
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/callbacks.rb | spec/models/callbacks.rb | class Artist
include Mongoid::Document
field :name
embeds_many :songs
embeds_many :labels
before_create :before_create_stub
after_create :create_songs
before_save :before_save_stub
before_destroy :before_destroy_stub
protected
def before_create_stub
true
end
def before_save_stub
true
end
def before_destroy_stub
true
end
def create_songs
2.times { |n| songs.create!(:title => "#{n}") }
end
end
class Song
include Mongoid::Document
field :title
embedded_in :artist
end
class Label
include Mongoid::Document
field :name
embedded_in :artist
before_validation :cleanup
private
def cleanup
self.name = self.name.downcase.capitalize
end
end
class ValidationCallback
include Mongoid::Document
field :history, :type => Array, :default => []
validate do
self.history << :validate
end
before_validation { self.history << :before_validation }
after_validation { self.history << :after_validation }
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/patient.rb | spec/models/patient.rb | class Email
include Mongoid::Document
field :address
validates_uniqueness_of :address
embedded_in :patient
end
class Patient
include Mongoid::Document
field :title
store_in :inpatient
embeds_many :addresses, :as => :addressable
embeds_one :email
validates_presence_of :title, :on => :create
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/player.rb | spec/models/player.rb | class Player
include Mongoid::Document
field :active, :type => Boolean
field :frags, :type => Integer
field :deaths, :type => Integer
field :status
named_scope :active, criteria.where(:active => true) do
def extension
"extension"
end
end
named_scope :inactive, :where => { :active => false }
named_scope :frags_over, lambda { |count| { :where => { :frags.gt => count } } }
named_scope :deaths_under, lambda { |count| criteria.where(:deaths.lt => count) }
scope :deaths_over, lambda { |count| criteria.where(:deaths.gt => count) }
class << self
def alive
criteria.where(:status => "Alive")
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/vet_visit.rb | spec/models/vet_visit.rb | class VetVisit
include Mongoid::Document
field :date, :type => Date
embedded_in :pet
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/address.rb | spec/models/address.rb | class Address
include Mongoid::Document
attr_accessor :mode
field :address_type
field :number, :type => Integer
field :street
field :city
field :state
field :post_code
field :parent_title
field :services, :type => Array
field :latlng, :type => Array
key :street
embeds_many :locations
embedded_in :addressable, :polymorphic => true do
def extension
"Testing"
end
def doctor?
title == "Dr"
end
end
accepts_nested_attributes_for :locations
referenced_in :account
scope :without_postcode, where(:postcode => nil)
named_scope :rodeo, where(:street => "Rodeo Dr") do
def mansion?
all? { |address| address.street == "Rodeo Dr" }
end
end
validates_presence_of :street, :on => :update
validates_format_of :street, :with => /\D/, :allow_nil => true
def set_parent=(set = false)
self.parent_title = addressable.title if set
end
def <=>(other)
street <=> other.street
end
class << self
def california
where(:state => "CA")
end
def homes
where(:address_type => "Home")
end
def streets
all.map(&:street)
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/house.rb | spec/models/house.rb | class House
include Mongoid::Document
field :name, :type => String
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/login.rb | spec/models/login.rb | class Login
include Mongoid::Document
field :username
key :username
validates_uniqueness_of :username
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/location.rb | spec/models/location.rb | class Location
include Mongoid::Document
field :name
embedded_in :address
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/comment.rb | spec/models/comment.rb | class Comment
include Mongoid::Document
include Mongoid::Versioning
include Mongoid::Timestamps
field :title, :type => String
field :text, :type => String
key :text, :type => String
referenced_in :movie
referenced_in :rating
validates :title, :presence => true
validates :movie, :rating, :associated => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/tracking_id_validation_history.rb | spec/models/tracking_id_validation_history.rb | # These models are spcific to test for Github #313.
module MyCompany
module Model
class TrackingId
include Mongoid::Document
include Mongoid::Timestamps
store_in :tracking_ids
embeds_many :validation_history, :class_name => "MyCompany::Model::TrackingIdValidationHistory"
end
end
end
module MyCompany
module Model
# A TrackingId validation state change
class TrackingIdValidationHistory
include Mongoid::Document
field :old_state, :type => String
field :new_state, :type => String
field :when_changed, :type => DateTime
attr_protected :_id
embedded_in :tracking_id, :class_name => "MyCompany::Model::TrackingId"
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/name.rb | spec/models/name.rb | class Name
include Mongoid::Document
field :first_name
field :last_name
field :parent_title
key :first_name, :last_name
embeds_many :translations
embedded_in :namable, :polymorphic => true
def set_parent=(set = false)
self.parent_title = namable.title if set
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/override.rb | spec/models/override.rb | class Override
include Mongoid::Document
def self.public_method
end
protected
def self.protected_method
end
private
def self.private_method
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/rating.rb | spec/models/rating.rb | class Rating
include Mongoid::Document
field :value, :type => Integer
referenced_in :ratable, :polymorphic => true
references_many :comments
validates_numericality_of :value, :less_than => 100, :allow_nil => true
validates :ratable, :associated => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/favorite.rb | spec/models/favorite.rb | class Favorite
include Mongoid::Document
field :title
validates_uniqueness_of :title, :case_sensitive => false
embedded_in :perp, :inverse_of => :favorites
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/post.rb | spec/models/post.rb | class Post
include Mongoid::Document
include Mongoid::MultiParameterAttributes
include Mongoid::Versioning
include Mongoid::Timestamps
field :title, :type => String
field :content, :type => String
field :rating, :type => Integer
belongs_to :person
belongs_to :author, :foreign_key => :author_id, :class_name => "User"
has_and_belongs_to_many :tags
has_many :videos, :validate => false
scope :recent, where(:created_at => { "$lt" => Time.now, "$gt" => 30.days.ago })
scope :posting, where(:content.in => [ "Posting" ])
validates_format_of :title, :without => /\$\$\$/
class << self
def old
where(:created_at => { "$lt" => 30.days.ago })
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/bar.rb | spec/models/bar.rb | class Bar
include Mongoid::Document
include Mongoid::Spacial::Document
field :name, :type => String
field :location, :type => Array, :spacial => true
references_one :rating, :as => :ratable
spacial_index :location
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/river.rb | spec/models/river.rb | class River
include Mongoid::Document
include Mongoid::Spacial::Document
field :name, type: String
field :length, type: Integer
field :average_discharge, type: Integer
field :source, type: Array, spacial: true
# set return_array to true if you do not want a hash returned all the time
field :mouth, type: Array, spacial: {lat: 'latitude', lng: 'longitude'}
field :mouth_array, type: Array, spacial: {return_array: true}
# simplified spacial indexing
# you can only index one field in mongodb < 1.9
spacial_index :source
# alternatives
# index [[ :spacial, Mongo::GEO2D ]], {min:-400, max:400}
# index [[ :spacial, Mongo::GEO2D ]], {bit:32}
# index [[ :spacial, Mongo::GEO2D ],:name]
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/video.rb | spec/models/video.rb | class Video
include Mongoid::Document
field :title
embedded_in :person
referenced_in :post
referenced_in :game
default_scope asc(:title)
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/question.rb | spec/models/question.rb | class Question
include Mongoid::Document
field :content
embedded_in :survey
embeds_many :answers
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/user_account.rb | spec/models/user_account.rb | class UserAccount
include Mongoid::Document
field :username
field :name
field :email
validates_uniqueness_of :username, :message => "is not unique"
validates_uniqueness_of :email, :message => "is not unique", :case_sensitive => false
validates_length_of :name, :minimum => 2, :allow_nil => true
references_and_referenced_in_many :people
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/acolyte.rb | spec/models/acolyte.rb | class Acolyte
include Mongoid::Document
field :status
field :name
scope :active, where(:status => "active")
default_scope asc(:name)
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/drug.rb | spec/models/drug.rb | class Drug
include Mongoid::Document
field :name, :type => String
referenced_in :person
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/service.rb | spec/models/service.rb | class Service
include Mongoid::Document
field :sid
embedded_in :person
validates_numericality_of :sid
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/role.rb | spec/models/role.rb | class Role
include Mongoid::Document
field :name, :type => String
recursively_embeds_many
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/phone.rb | spec/models/phone.rb | class Phone
include Mongoid::Document
field :number
key :number
embeds_one :country_code
embedded_in :person
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/survey.rb | spec/models/survey.rb | class Survey
include Mongoid::Document
embeds_many :questions
accepts_nested_attributes_for :questions, :reject_if => lambda{ |a| a[:content].blank? }, :allow_destroy => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/person.rb | spec/models/person.rb | class Person
include Mongoid::Document
include Mongoid::MultiParameterAttributes
include Mongoid::Timestamps
include Mongoid::Versioning
attr_accessor :mode
class_attribute :somebody_elses_important_class_options
self.somebody_elses_important_class_options = { :keep_me_around => true }
field :title
field :terms, :type => Boolean
field :pets, :type => Boolean, :default => false
field :age, :type => Integer, :default => 100
field :dob, :type => Date
field :employer_id
field :lunch_time, :type => Time
field :aliases, :type => Array
field :map, :type => Hash
field :score, :type => Integer
field :blood_alcohol_content, :type => Float, :default => lambda{ 0.0 }
field :last_drink_taken_at, :type => Date, :default => lambda { 1.day.ago.in_time_zone("Alaska") }
field :ssn
field :owner_id, :type => Integer
field :security_code
field :reading, :type => Object
field :bson_id, :type => BSON::ObjectId
index :age
index :addresses
index :dob
index :name
index :title
index :ssn, :unique => true
validates_format_of :ssn, :without => /\$\$\$/
attr_reader :rescored
attr_protected :security_code, :owner_id
embeds_many :favorites, :order => :title.desc, :inverse_of => :perp
embeds_many :videos, :order => [[ :title, :asc ]]
embeds_many :phone_numbers, :class_name => "Phone"
embeds_many :addresses, :as => :addressable do
def extension
"Testing"
end
def find_by_street(street)
@target.select { |doc| doc.street == street }
end
end
embeds_many :address_components
embeds_many :services
embeds_one :pet, :class_name => "Animal"
embeds_one :name, :as => :namable do
def extension
"Testing"
end
def dawkins?
first_name == "Richard" && last_name == "Dawkins"
end
end
embeds_one :quiz
accepts_nested_attributes_for :addresses
accepts_nested_attributes_for :name, :update_only => true
accepts_nested_attributes_for :pet, :allow_destroy => true
accepts_nested_attributes_for :game, :allow_destroy => true
accepts_nested_attributes_for :favorites, :allow_destroy => true, :limit => 5
accepts_nested_attributes_for :posts
accepts_nested_attributes_for :preferences
accepts_nested_attributes_for :quiz
references_one :game, :dependent => :destroy do
def extension
"Testing"
end
end
references_many \
:posts,
:dependent => :delete,
:order => :rating.desc do
def extension
"Testing"
end
end
references_many :paranoid_posts
references_and_referenced_in_many \
:preferences,
:index => true,
:dependent => :nullify,
:autosave => true,
:order => :value.desc
references_and_referenced_in_many :user_accounts
references_and_referenced_in_many :houses
references_many :drugs, :autosave => true
references_one :account, :autosave => true
references_and_referenced_in_many \
:administrated_events,
:class_name => 'Event',
:inverse_of => :administrators,
:dependent => :nullify
scope :minor, where(:age.lt => 18)
scope :without_ssn, without(:ssn)
def score_with_rescoring=(score)
@rescored = score.to_i + 20
self.score_without_rescoring = score
end
alias_method_chain :score=, :rescoring
def update_addresses
addresses.each do |address|
address.street = "Updated Address"
end
end
def employer=(emp)
self.employer_id = emp.id
end
class << self
def accepted
criteria.where(:terms => true)
end
def knight
criteria.where(:title => "Sir")
end
def old
criteria.where(:age => { "$gt" => 50 })
end
end
end
class Doctor < Person
field :specialty
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/circus.rb | spec/models/circus.rb | class Circus
include Mongoid::Document
field :name
embeds_many :animals
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/alert.rb | spec/models/alert.rb | class Alert
include Mongoid::Document
field :message, :type => String
referenced_in :account
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/wiki_page.rb | spec/models/wiki_page.rb | class WikiPage
include Mongoid::Document
include Mongoid::Versioning
field :title, :type => String
max_versions 5
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/ghost.rb | spec/models/ghost.rb | class Ghost
include Mongoid::Document
field :name, :type => String
referenced_in :movie, :autosave => true
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/fruits.rb | spec/models/fruits.rb | module Fruits
class Apple
include Mongoid::Document
references_many :bananas, :class_name => "Fruits::Banana"
end
class Banana
include Mongoid::Document
referenced_in :apple, :class_name => "Fruits::Apple"
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/models/user.rb | spec/models/user.rb | class User
include Mongoid::Document
field :name
references_one :account, :foreign_key => :creator_id
references_many :posts, :foreign_key => :author_id
references_many :descriptions
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/spacial_spec.rb | spec/unit/mongoid/spacial_spec.rb | require "spec_helper"
describe Mongoid::Spacial do
describe '#distance' do
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/criterion/within_spacial_spec.rb | spec/unit/mongoid/criterion/within_spacial_spec.rb | require "spec_helper"
describe Mongoid::Criterion::WithinSpacial do
let(:within) do
{
:box => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "box"),
:polygon => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "polygon"),
:center => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "center"),
:center_sphere => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "box"),
}
end
WITHIN = {
:box =>
{
'Array of Arrays' => [[10,20], [15,25]],
'Array of Hashes' => [{ x: 10, y: 20 }, { x: 15, y: 25 }],
'Hash of Hashes' => { a: { x: 10, y: 20 }, b: { x: 15, y: 25 }}
},
:polygon =>
{
'Array of Arrays' => [[10,20], [15,25]],
'Array of Hashes' => [{ x: 10, y: 20 }, { x: 15, y: 25 }],
'Hash of Hashes' => { a: { x: 10, y: 20 }, b: { x: 15, y: 25 }}
},
:center =>
{
'Point' => [[1,2],5],
'Hash Point' => {:point => [-73.98, 40.77], :max => 5},
'Hash Point Unit' => {:point => [-73.98, 40.77], :max => 5, :unit => :km}
},
:center_sphere =>
{
'Point' => [[1,2],5],
'Hash Point' => {:point => [-73.98, 40.77], :max => 5},
'Hash Point Unit' => {:point => [-73.98, 40.77], :max => 5, :unit => :km}
}
}
context "#to_mongo_query" do
WITHIN.each do |shape, points|
points.each do |input_name,input|
it "#{shape} should generate a query with #{input_name}" do
within[shape].to_mongo_query(input).should be_a_kind_of(Hash)
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/criterion/near_spacial_spec.rb | spec/unit/mongoid/criterion/near_spacial_spec.rb | require "spec_helper"
describe Mongoid::Criterion::NearSpacial do
let(:within) do
{
:flat => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "near"),
:sphere => Mongoid::Criterion::WithinSpacial.new(:key => :field, :operator => "nearSphere"),
}
end
NEAR = {
:flat =>
{
'Point' => [[1,2],5],
'Hash Point' => {:point => [-73.98, 40.77], :max => 5},
'Hash Point Unit' => {:point => [-73.98, 40.77], :max => 5, :unit => :km}
},
:sphere =>
{
'Point' => [[1,2],5],
'Hash Point' => {:point => [-73.98, 40.77], :max => 5},
'Hash Point Unit' => {:point => [-73.98, 40.77], :max => 5, :unit => :km}
}
}
context "#to_mongo_query" do
NEAR.each do |shape, points|
points.each do |input_name,input|
it "#{shape} should generate a query with #{input_name}" do
within[shape].to_mongo_query(input).should be_a_kind_of(Hash)
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/criterion/complex_spec.rb | spec/unit/mongoid/criterion/complex_spec.rb | require "spec_helper"
describe Mongoid::Criterion::Complex do
let(:complex) { Mongoid::Criterion::Complex.new(:key => :field, :operator => "gt") }
let(:value) { 40 }
context "#to_mongo_query" do
it "should turn value into appropriate query" do
complex.to_mongo_query(value).should == {"$gt" => value}
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/criterion/inclusion_spec.rb | spec/unit/mongoid/criterion/inclusion_spec.rb | ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false | |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/unit/mongoid/spacial/formulas_spec.rb | spec/unit/mongoid/spacial/formulas_spec.rb | require "spec_helper"
describe Mongoid::Spacial::Formulas do
context "#n_vector" do
it {
bna = [-86.67, 36.12]
lax = [-118.40, 33.94]
dist1 = Mongoid::Spacial::Formulas.n_vector(bna, lax)
dist2 = Mongoid::Spacial::Formulas.n_vector(lax, bna)
# target is 0.45306
dist1.should be_within(0.00001).of(0.45306)
dist2.should be_within(0.00001).of(0.45306)
}
it {
# actual distance 2471.788
jfk = [-73.77694444, 40.63861111 ]
lax = [-118.40, 33.94]
dist = Mongoid::Spacial::Formulas.n_vector(jfk, lax) * Mongoid::Spacial.earth_radius[:mi]
dist.should be_within(1).of(2469)
}
end
context "#haversine" do
it {
# actual distance 2471.788
jfk = [-73.77694444, 40.63861111 ]
lax = [-118.40, 33.94]
dist = Mongoid::Spacial::Formulas.haversine(jfk, lax) * Mongoid::Spacial.earth_radius[:mi]
dist.should be_within(1).of(2469)
}
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/functional/mongoid/spacial_spec.rb | spec/functional/mongoid/spacial_spec.rb | require "spec_helper"
describe Mongoid::Spacial do
describe '#distance' do
it "should calculate 2d by default" do
Mongoid::Spacial.distance([0,0],[3,4]).should == 5
end
it "should calculate 2d distances using degrees" do
Mongoid::Spacial.distance([0,0],[3,4], :unit=>:mi).should == 5*Mongoid::Spacial::EARTH_RADIUS[:mi]*Mongoid::Spacial::RAD_PER_DEG
end
it "should calculate 3d distances by default" do
Mongoid::Spacial.distance([-73.77694444, 40.63861111 ],[-118.40, 33.94],:unit=>:mi, :spherical => true).to_i.should be_within(1).of(2469)
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/functional/mongoid/criterion/inclusion_spec.rb | spec/functional/mongoid/criterion/inclusion_spec.rb | require "spec_helper"
describe Mongoid::Criterion::Inclusion do
before do
Person.delete_all
end
describe "#where" do
let(:dob) do
33.years.ago.to_date
end
let(:lunch_time) do
30.minutes.ago
end
let!(:person) do
Person.create(
:title => "Sir",
:dob => dob,
:lunch_time => lunch_time,
:age => 33,
:aliases => [ "D", "Durran" ],
:things => [ { :phone => 'HTC Incredible' } ]
)
end
context "when providing 24 character strings" do
context "when the field is not an id field" do
let(:string) do
BSON::ObjectId.new.to_s
end
let!(:person) do
Person.create(:title => string)
end
let(:from_db) do
Person.where(:title => string)
end
it "does not convert the field to a bson id" do
from_db.should == [ person ]
end
end
end
context "when providing string object ids" do
context "when providing a single id" do
let(:from_db) do
Person.where(:_id => person.id.to_s).first
end
it "returns the matching documents" do
from_db.should == person
end
end
end
context "chaining multiple wheres" do
context "when chaining on the same key" do
let(:from_db) do
Person.where(:title => "Maam").where(:title => "Sir")
end
it "overrides the previous key" do
from_db.should == [ person ]
end
end
context "with different criteria on the same key" do
it "merges criteria" do
Person.where(:age.gt => 30).where(:age.lt => 40).should == [person]
end
it "typecasts criteria" do
before_dob = (dob - 1.month).to_s
after_dob = (dob + 1.month).to_s
Person.where(:dob.gt => before_dob).and(:dob.lt => after_dob).should == [person]
end
end
end
context "with untyped criteria" do
it "typecasts integers" do
Person.where(:age => "33").should == [ person ]
end
it "typecasts datetimes" do
Person.where(:lunch_time => lunch_time.to_s).should == [ person ]
end
it "typecasts dates" do
Person.where({:dob => dob.to_s}).should == [ person ]
end
it "typecasts times with zones" do
time = lunch_time.in_time_zone("Alaska")
Person.where(:lunch_time => time).should == [ person ]
end
it "typecasts array elements" do
Person.where(:age.in => [17, "33"]).should == [ person ]
end
it "typecasts size criterion to integer" do
Person.where(:aliases.size => "2").should == [ person ]
end
it "typecasts exists criterion to boolean" do
Person.where(:score.exists => "f").should == [ person ]
end
end
context "with multiple complex criteria" do
before do
Person.create(:title => "Mrs", :age => 29)
Person.create(:title => "Ms", :age => 41)
end
it "returns those matching both criteria" do
Person.where(:age.gt => 30, :age.lt => 40).should == [person]
end
it "returns nothing if in and nin clauses cancel each other out" do
Person.any_in(:title => ["Sir"]).not_in(:title => ["Sir"]).should == []
end
it "returns nothing if in and nin clauses cancel each other out ordered the other way" do
Person.not_in(:title => ["Sir"]).any_in(:title => ["Sir"]).should == []
end
it "returns the intersection of in and nin clauses" do
Person.any_in(:title => ["Sir", "Mrs"]).not_in(:title => ["Mrs"]).should == [person]
end
it "returns the intersection of two in clauses" do
Person.where(:title.in => ["Sir", "Mrs"]).where(:title.in => ["Sir", "Ms"]).should == [person]
end
end
context "with complex criterion" do
context "#all" do
it "returns those matching an all clause" do
Person.where(:aliases.all => ["D", "Durran"]).should == [person]
end
end
context "#exists" do
it "returns those matching an exists clause" do
Person.where(:title.exists => true).should == [person]
end
end
context "#gt" do
it "returns those matching a gt clause" do
Person.where(:age.gt => 30).should == [person]
end
end
context "#gte" do
it "returns those matching a gte clause" do
Person.where(:age.gte => 33).should == [person]
end
end
context "#in" do
it "returns those matching an in clause" do
Person.where(:title.in => ["Sir", "Madam"]).should == [person]
end
it "allows nil" do
Person.where(:ssn.in => [nil]).should == [person]
end
end
context "#lt" do
it "returns those matching a lt clause" do
Person.where(:age.lt => 34).should == [person]
end
end
context "#lte" do
it "returns those matching a lte clause" do
Person.where(:age.lte => 33).should == [person]
end
end
context "#ne" do
it "returns those matching a ne clause" do
Person.where(:age.ne => 50).should == [person]
end
end
context "#nin" do
it "returns those matching a nin clause" do
Person.where(:title.nin => ["Esquire", "Congressman"]).should == [person]
end
end
context "#size" do
it "returns those matching a size clause" do
Person.where(:aliases.size => 2).should == [person]
end
end
context "#match" do
it "returns those matching a partial element in a list" do
Person.where(:things.matches => { :phone => "HTC Incredible" }).should == [person]
end
end
end
context "Geo Spacial Complex Where" do
let!(:home) do
[-73.98,40.77]
end
describe "#near" do
before do
Bar.delete_all
Bar.create_indexes
end
let!(:berlin) do
Bar.create(:location => [ 52.30, 13.25 ])
end
let!(:prague) do
Bar.create(:location => [ 50.5, 14.26 ])
end
let!(:paris) do
Bar.create(:location => [ 48.48, 2.20 ])
end
it "returns the documents sorted closest to furthest" do
Bar.where(:location.near => [ 41.23, 2.9 ]).should == [ paris, prague, berlin ]
end
it "returns the documents sorted closest to furthest" do
Bar.where(:location.near => {:point=>[ 41.23, 2.9 ],:max => 20}).should == [ paris, prague, berlin ]
end
it "returns the documents sorted closest to furthest" do
Bar.where(:location.near_sphere => [ 41.23, 2.9 ]).should == [ paris, prague, berlin ]
end
end
context "#within" do
context ":box, :polygon" do
before do
Bar.delete_all
Bar.create_indexes
end
let!(:berlin) do
Bar.create(:name => 'berlin', :location => [ 52.30, 13.25 ])
end
let!(:prague) do
Bar.create(:name => 'prague',:location => [ 50.5, 14.26 ])
end
let!(:paris) do
Bar.create(:name => 'prague',:location => [ 48.48, 2.20 ])
end
it "returns the documents within a box" do
Bar.where(:location.within(:box) => [[ 47, 1 ],[ 49, 3 ]]).should == [ paris ]
end
it "returns the documents within a polygon", :if => (Mongoid.master.connection.server_version >= '1.9') do
Bar.where(:location.within(:polygon) => [[ 47, 1 ],[49,1.5],[ 49, 3 ],[46,5]]).should == [ paris ]
end
it "returns the documents within a center" do
Bar.where(:location.within(:center) => [[ 47, 1 ],4]).should == [ paris ]
end
it "returns the documents within a center_sphere" do
Bar.where(:location.within(:center_sphere) => [[ 48, 2 ],0.1]).should == [ paris ]
end
end
context ":circle :center_sphere" do
before do
Bar.delete_all
Bar.create_indexes
end
let!(:mile1) do
Bar.create(:name => 'mile1', :location => [-73.997345, 40.759382])
end
let!(:mile3) do
Bar.create(:name => 'mile2', :location => [-73.927088, 40.752151])
end
let!(:mile7) do
Bar.create(:name => 'mile3', :location => [-74.0954913, 40.7161472])
end
let!(:mile11) do
Bar.create(:name => 'mile4', :location => [-74.0604951, 40.9178011])
end
it "returns the documents within a center_sphere" do
Bar.where(:location.within(:center_sphere) => {:point => home,:max => 2, :unit => :mi}).should == [ mile1 ]
end
it "returns the documents within a center_sphere" do
Bar.where(:location.within(:center_sphere) => {:point => home,:max => 4, :unit => :mi}).should include(mile3)
end
it "returns the documents within a center_sphere" do
Bar.where(:location.within(:center_sphere) => {:point => home,:max => 8, :unit => :mi}).should include(mile7)
end
it "returns the documents within a center_sphere" do
Bar.where(:location.within(:center_sphere) => {:point => home,:max => 12, :unit => :mi}).should include(mile11)
end
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/functional/mongoid/spacial/geo_near_results_spec.rb | spec/functional/mongoid/spacial/geo_near_results_spec.rb | require "spec_helper"
describe Mongoid::Spacial::GeoNearResults do
before(:all) do
Bar.delete_all
Bar.create_indexes
50.times do |i|
Bar.create(:name => i.to_s, :location => [rand(358)-179,rand(358)-179])
end
end
before(:each) do
while Bar.count < 50
end
end
context ":paginator :array" do
let(:bars) { Bar.geo_near([1,1]) }
let(:sorted_bars) {
bars = Bar.geo_near([1,1])
bars.sort_by! {|b| b.name.to_i}
bars
}
[nil,1,2].each do |page|
it "page=#{page} should have 25" do
bars.page(page).size.should == 25
end
end
[1,2].each do |page|
it "modified result should keep order after pagination" do
sorted_bars.page(page).should == sorted_bars.slice((page-1)*25,25)
end
end
{ nil => 25, 20 => 20 , 30 => 20, 50 => 0}.each do |per, total|
it "page=2 per=#{per} should have #{total}" do
bars.per(per).page(2).size.should == total
bars.page(2).per(per).size.should == total
end
end
it "page=3 should have 0" do
bars.page(3).size.should == 0
end
it "per=5" do
bars.per(5).size.should == 5
end
it "page=10 per=5" do
bars.per(5).page(10).should == bars[45..50]
end
end
context ":paginator :kaminari" do
let!(:near) {Bar.geo_near([1,1]).page(1)}
it "should have current_page" do
near.current_page.should == 1
end
it "should have num_pages" do
near.total_entries.should == 50
near.num_pages.should == 2
end
it "should have limit_value" do
near.limit_value.should == 25
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/spec/functional/mongoid/contexts/mongo_spec.rb | spec/functional/mongoid/contexts/mongo_spec.rb | require "spec_helper"
describe Mongoid::Contexts::Mongo do
describe "#geo_near" do
before do
Bar.delete_all
Bar.create_indexes
end
let!(:jfk) do
Bar.create(:name => 'jfk', :location => [-73.77694444, 40.63861111 ])
end
let!(:lax) do
Bar.create(:name => 'lax', :location => [-118.40, 33.94])
end
it "should work with specifying specific center and different location attribute on collction" do
Bar.geo_near(lax.location, :spherical => true).should == [lax, jfk]
Bar.geo_near(jfk.location, :spherical => true).should == [jfk, lax]
end
context 'option' do
context ':num' do
it "should limit number of results to 1" do
Bar.geo_near(jfk.location, :num => 1).size.should == 1
end
end
context ':maxDistance' do
it "should get 1 item" do
Bar.geo_near(lax.location, :spherical => true, :max_distance => 2465/Mongoid::Spacial.earth_radius[:mi]).size.should == 1
end
it "should get 2 items" do
Bar.geo_near(lax.location, :spherical => true, :max_distance => 2480/Mongoid::Spacial.earth_radius[:mi]).size.should == 2
end
end
context ':distance_multiplier' do
it "should multiply returned distance with multiplier" do
Bar.geo_near(lax.location, :spherical => true, :distance_multiplier=> Mongoid::Spacial.earth_radius[:mi]).second.geo[:distance].to_i.should be_within(1).of(2469)
end
end
context ':unit' do
it "should multiply returned distance with multiplier" do
Bar.geo_near(lax.location, :spherical => true, :unit => :mi).second.geo[:distance].to_i.should be_within(1).of(2469)
end
it "should convert max_distance to radians with unit" do
Bar.geo_near(lax.location, :spherical => true, :max_distance => 2465, :unit => :mi).size.should == 1
end
end
context ':query' do
it "should filter using extra query option" do
# two record in the collection, only one's name is Munich
Bar.geo_near(jfk.location, :query => {:name => jfk.name}).should == [jfk]
end
end
end
context 'criteria chaining' do
it "should filter by where" do
Bar.where(:name => jfk.name).geo_near(jfk.location).should == [jfk]
Bar.any_of({:name => jfk.name},{:name => lax.name}).geo_near(jfk.location).should == [jfk,lax]
end
it 'should skip 1' do
Bar.skip(1).geo_near(jfk.location).size.should == 1
end
it 'should limit 1' do
Bar.limit(1).geo_near(jfk.location).size.should == 1
end
end
end
context ':page' do
before(:all) do
Bar.delete_all
Bar.create_indexes
50.times do
Bar.create({:location => [rand(360)-180,rand(360)-180]})
end
end
context ":paginator :array" do
[nil,1,2].each do |page|
it "page=#{page} should have 25" do
Bar.geo_near([1,1], :page => page).size.should == 25
end
end
it "page=3 should have 0" do
Bar.geo_near([1,1], :page => 20).size.should == 0
end
it "per_page=5" do
Bar.geo_near([1,1], :page => 1, :per_page => 5).size.should == 5
end
end
context ":paginator :kaminari" do
let(:near) {Bar.geo_near([1,1], :page => 1)}
it "should have current_page" do
near.current_page.should == 1
end
it "should have num_pages" do
pending
near.num_pages.should == 2
end
it "should have limit_value" do
near.limit_value.should == 25
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial.rb | lib/mongoid_spacial.rb | require 'mongoid'
require 'active_support/core_ext/string/inflections'
require 'active_support/concern'
require 'mongoid_spacial/contexts/mongo'
require 'mongoid_spacial/criteria'
require 'mongoid_spacial/criterion'
require 'mongoid_spacial/extentions/hash/criteria_helpers'
require 'mongoid_spacial/extentions/symbol/inflections'
require 'mongoid_spacial/field_option'
require 'mongoid_spacial/finders'
require 'mongoid_spacial/spacial'
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/finders.rb | lib/mongoid_spacial/finders.rb | module Mongoid #:nodoc:
module Finders
delegate :geo_near, :to => :criteria
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial.rb | lib/mongoid_spacial/spacial.rb | require 'mongoid_spacial/spacial/core_ext'
require 'mongoid_spacial/spacial/formulas'
require 'mongoid_spacial/spacial/document'
require 'mongoid_spacial/spacial/geo_near_results'
module Mongoid
module Spacial
EARTH_RADIUS_KM = 6371 # taken directly from mongodb
EARTH_RADIUS = {
:km => EARTH_RADIUS_KM,
:m => EARTH_RADIUS_KM*1000,
:mi => EARTH_RADIUS_KM*0.621371192, # taken directly from mongodb
:ft => EARTH_RADIUS_KM*5280*0.621371192,
}
RAD_PER_DEG = Math::PI/180
LNG_SYMBOLS = [:x, :lon, :long, :lng, :longitude]
LAT_SYMBOLS = [:y, :lat, :latitude]
def self.distance(p1,p2,opts = {})
opts[:formula] ||= (opts[:spherical]) ? @@spherical_distance_formula : :pythagorean_theorem
p1 = p1.to_lng_lat if p1.respond_to?(:to_lng_lat)
p2 = p2.to_lng_lat if p2.respond_to?(:to_lng_lat)
rads = Formulas.send(opts[:formula], p1, p2)
if unit = earth_radius[opts[:unit]]
opts[:unit] = (rads.instance_variable_get("@radian")) ? unit : unit * RAD_PER_DEG
end
rads *= opts[:unit].to_f if opts[:unit]
rads
end
mattr_accessor :lng_symbols
@@lng_symbols = LNG_SYMBOLS.dup
mattr_accessor :lat_symbols
@@lat_symbols = LAT_SYMBOLS.dup
mattr_accessor :earth_radius
@@earth_radius = EARTH_RADIUS.dup
mattr_accessor :paginator
@@paginator = :array
mattr_accessor :default_per_page
@@default_per_page = 25
mattr_accessor :spherical_distance_formula
@@spherical_distance_formula = :n_vector
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/field_option.rb | lib/mongoid_spacial/field_option.rb | require 'ostruct'
# Field changes to Fields from mongoid 2.0 to mongoid 2.1
field = (defined?(Mongoid::Field)) ? Mongoid::Field : Mongoid::Fields
field.option :spacial do |model,field,options|
options = {} unless options.kind_of?(Hash)
lat_meth = options[:lat] || :lat
lng_meth = options[:lng] || :lng
model.class_eval do
self.spacial_fields ||= []
self.spacial_fields << field.name.to_sym if self.spacial_fields.kind_of? Array
define_method "distance_from_#{field.name}" do |*args|
self.distance_from(field.name, *args)
end
define_method field.name do
output = self[field.name] || [nil,nil]
output = {lng_meth => output[0], lat_meth => output[1]} unless options[:return_array]
return options[:class].new(output) if options[:class]
output
end
define_method "#{field.name}=" do |arg|
if arg.kind_of?(Hash) && arg[lng_meth] && arg[lat_meth]
arg = [arg[lng_meth].to_f, arg[lat_meth].to_f]
elsif arg.respond_to?(:to_lng_lat)
arg = arg.to_lng_lat
end
self[field.name]=arg
arg = [nil,nil] if arg.nil?
return arg[0..1] if options[:return_array]
h = {lng_meth => arg[0], lat_meth => arg[1]}
return h if options[:class].blank?
options[:class].new(h)
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criterion.rb | lib/mongoid_spacial/criterion.rb | require 'mongoid_spacial/criterion/complex'
require 'mongoid_spacial/criterion/near_spacial'
require 'mongoid_spacial/criterion/within_spacial'
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criteria.rb | lib/mongoid_spacial/criteria.rb | module Mongoid #:nodoc:
class Criteria
delegate :geo_near, :to => :context
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criterion/within_spacial.rb | lib/mongoid_spacial/criterion/within_spacial.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Criterion #:nodoc:
# WithinSpecial criterion is used when performing #within with symbols to get
# get a shorthand syntax for where clauses.
#
# @example Conversion of a simple to complex criterion.
# { :field => { "$within" => {'$center' => [20,30]} } }
# becomes:
# { :field.within(:center) => [20,30] }
class WithinSpacial < Complex
# Convert input to query for box, polygon, center, and centerSphere
#
# @example
# within = WithinSpacial.new(opts[:key] => 'point', :operator => 'center')
# within.to_mongo_query({:point => [20,30], :max => 5, :unit => :km}) #=>
#
# @param [Hash,Array] input Variable to conver to query
def to_mongo_query(input)
if ['box','polygon'].index(@operator)
input = input.values if input.kind_of?(Hash)
if input.respond_to?(:map)
input.map!{ |v| (v.respond_to?(:to_lng_lat)) ? v.to_lng_lat : v }
else
input
end
elsif ['center','centerSphere'].index(@operator)
if input.kind_of?(Hash) || input.kind_of?(ActiveSupport::OrderedHash)
raise ':point required to make valid query' unless input[:point]
input[:point] = input[:point].to_lng_lat if input[:point].respond_to?(:to_lng_lat)
if input[:max]
input[:max] = input[:max].to_f
if unit = Mongoid::Spacial.earth_radius[input[:unit]]
unit *= Mongoid::Spacial::RAD_PER_DEG unless operator =~ /sphere/i
input[:unit] = unit
end
input[:max] = input[:max]/input[:unit].to_f if input[:unit]
input = [input[:point],input[:max]]
else
input = input[:point]
end
end
if input.kind_of? Array
input[0] = input[0].to_lng_lat if input[0].respond_to?(:to_lng_lat)
end
end
{'$within' => {"$#{@operator}"=>input} }
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criterion/near_spacial.rb | lib/mongoid_spacial/criterion/near_spacial.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Criterion #:nodoc:
# NearSpecial criterion is used when performing #near with symbols to get
# get a shorthand syntax for where clauses.
#
# @example Coninputersion of a simple to complex criterion.
# { :field => { "$nearSphere" => => [20,30]}, '$maxDistance' => 5 }
# becomes:
# { :field.near(:sphere) => {:point => [20,30], :max => 5, :unit => :km} }
class NearSpacial < Complex
# Coninputert input to query for near or nearSphere
#
# @example
# near = NearSpacial.new(:key => :field, :operator => "near")
# near.to_mongo_query({:point => [:50,50], :max => 5, :unit => :km}) => { '$near : [50,50]' , '$maxDistance' : 5 }
#
# @param [Hash,Array] input input to coninputer to query
def to_mongo_query(input)
if input.kind_of?(Hash)
raise ':point required to make valid query' unless input[:point]
input[:point] = input[:point].to_lng_lat if input[:point].respond_to?(:to_lng_lat)
query = {"$#{operator}" => input[:point] }
if input[:max]
query['$maxDistance'] = input[:max].to_f
if unit = Mongoid::Spacial.earth_radius[input[:unit]]
unit *= Mongoid::Spacial::RAD_PER_DEG unless operator =~ /sphere/i
input[:unit] = unit
end
query['$maxDistance'] = query['$maxDistance']/input[:unit].to_f if input[:unit]
end
query
elsif input.kind_of? Array
if input.first.kind_of? Numeric
{"$#{operator}" => input }
else
input[0] = input[0].to_lng_lat if input[0].respond_to?(:to_lng_lat)
{"$#{operator}" => input[0], '$maxDistance' => input[1] }
end
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criterion/complex.rb | lib/mongoid_spacial/criterion/complex.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Criterion #:nodoc:
# Complex criterion are used when performing operations on symbols to get
# get a shorthand syntax for where clauses.
#
# Example:
#
# <tt>{ :field => { "$lt" => "value" } }</tt>
# becomes:
# <tt> { :field.lt => "value }</tt>
class Complex
def to_mongo_query v
{"$#{operator}" => v}
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/criterion/inclusion.rb | lib/mongoid_spacial/criterion/inclusion.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Criterion #:nodoc:
module Inclusion
def near(attributes = {})
update_selector(attributes, "$near")
end
def near_sphere(attributes = {})
update_selector(attributes, "$near")
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/extentions/hash/criteria_helpers.rb | lib/mongoid_spacial/extentions/hash/criteria_helpers.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Extensions #:nodoc:
module Hash #:nodoc:
module CriteriaHelpers #:nodoc:
def expand_complex_criteria
hsh = {}
each_pair do |k,v|
if k.respond_to?(:key) && k.respond_to?(:to_mongo_query)
hsh[k.key] ||= {}
hsh[k.key].merge!(k.to_mongo_query(v))
else
hsh[k] = v
end
end
hsh
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/extentions/symbol/inflections.rb | lib/mongoid_spacial/extentions/symbol/inflections.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Extensions #:nodoc:
module Symbol #:nodoc:
module Inflections #:nodoc:
# return a class that will accept a value to convert the query correctly for near
#
# @param [Symbol] calc This accepts :sphere
#
# @return [Criterion::NearSpacial]
def near(calc = :flat)
Criterion::NearSpacial.new(:operator => get_op('near',calc), :key => self)
end
# alias for self.near(:sphere)
#
# @return [Criterion::NearSpacial]
def near_sphere
self.near(:sphere)
end
# @param [Symbol] shape :box,:polygon,:center,:center_sphere
#
# @return [Criterion::WithinSpacial]
def within(shape)
shape = get_op(:center,:sphere) if shape == :center_sphere
Criterion::WithinSpacial.new(:operator => shape.to_s , :key => self)
end
private
def get_op operator, calc
if calc.to_sym == :sphere && Mongoid.master.connection.server_version >= '1.7'
"#{operator}Sphere"
elsif calc.to_sym == :sphere
raise "MongoDB Server version #{Mongoid.master.connection.server_version} does not have Spherical Calculation"
else
operator.to_s
end
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial/version.rb | lib/mongoid_spacial/spacial/version.rb | module Mongoid
module Spacial
VERSION = "0.2.17"
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial/core_ext.rb | lib/mongoid_spacial/spacial/core_ext.rb | class Array
def to_lng_lat
self[0..1].map(&:to_f)
end
end
class Hash
def to_lng_lat
raise "Hash must have at least 2 items" if self.size < 2
[to_lng, to_lat]
end
def to_lat
v = (Mongoid::Spacial.lat_symbols & self.keys).first
return self[v].to_f if !v.nil? && self[v]
raise "Hash must contain #{Mongoid::Spacial.lat_symbols.inspect} if ruby version is less than 1.9" if RUBY_VERSION.to_f < 1.9
raise "Hash cannot contain #{Mongoid::Spacial.lng_symbols.inspect} as the second item if there is no #{Mongoid::Spacial.lat_symbols.inspect}" if Mongoid::Spacial.lng_symbols.index(self.keys[1])
self.values[1].to_f
end
def to_lng
v = (Mongoid::Spacial.lng_symbols & self.keys).first
return self[v].to_f if !v.nil? && self[v]
raise "Hash cannot contain #{Mongoid::Spacial.lat_symbols.inspect} as the first item if there is no #{Mongoid::Spacial.lng_symbols.inspect}" if Mongoid::Spacial.lat_symbols.index(self.keys[0])
self.values[0].to_f
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial/formulas.rb | lib/mongoid_spacial/spacial/formulas.rb | module Mongoid
module Spacial
module Formulas
class << self
def n_vector(point1,point2)
p1 = point1.map{|deg| deg * RAD_PER_DEG}
p2 = point2.map{|deg| deg * RAD_PER_DEG}
sin_x1 = Math.sin(p1[0])
cos_x1 = Math.cos(p1[0])
sin_y1 = Math.sin(p1[1])
cos_y1 = Math.cos(p1[1])
sin_x2 = Math.sin(p2[0])
cos_x2 = Math.cos(p2[0])
sin_y2 = Math.sin(p2[1])
cos_y2 = Math.cos(p2[1])
cross_prod = (cos_y1*cos_x1 * cos_y2*cos_x2) +
(cos_y1*sin_x1 * cos_y2*sin_x2) +
(sin_y1 * sin_y2)
return cross_prod > 0 ? 0 : Math::PI if (cross_prod >= 1 || cross_prod <= -1)
d = Math.acos(cross_prod)
d.instance_variable_set("@radian", true)
d
end
def haversine(point1,point2)
p1 = point1.map{|deg| deg * RAD_PER_DEG}
p2 = point2.map{|deg| deg * RAD_PER_DEG}
dlon = p2[0] - p1[0]
dlat = p2[1] - p1[1]
a = (Math.sin(dlat/2))**2 + Math.cos(p1[1]) * Math.cos(p2[1]) * (Math.sin(dlon/2))**2
d = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))
d.instance_variable_set("@radian", true)
d
end
def pythagorean_theorem(p1, p2)
Math.sqrt(((p2[0] - p1[0]) ** 2) + ((p2[1] - p1[1]) ** 2))
end
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial/geo_near_results.rb | lib/mongoid_spacial/spacial/geo_near_results.rb | module Mongoid
module Spacial
class GeoNearResults < Array
attr_reader :stats, :document, :_original_array, :_original_opts
attr_accessor :opts
def initialize(document,results,opts = {})
raise "#{document.name} class must include Mongoid::Spacial::Document" unless document.respond_to?(:spacial_fields_indexed)
@document = document
@opts = opts
@_original_opts = opts.clone
@stats = results['stats'] || {}
@opts[:skip] ||= 0
@_original_array = results['results'].collect do |result|
res = Mongoid::Factory.from_db(@document, result.delete('obj'))
res.geo = {}
# camel case is awkward in ruby when using variables...
if result['dis']
res.geo[:distance] = result.delete('dis').to_f
end
result.each do |key,value|
res.geo[key.snakecase.to_sym] = value
end
# dist_options[:formula] = opts[:formula] if opts[:formula]
@opts[:calculate] = @document.spacial_fields_indexed if @document.spacial_fields_indexed.kind_of?(Array) && @opts[:calculate] == true
if @opts[:calculate]
@opts[:calculate] = [@opts[:calculate]] unless @opts[:calculate].kind_of? Array
@opts[:calculate] = @opts[:calculate].map(&:to_sym) & geo_fields
if @document.spacial_fields_indexed.kind_of?(Array) && @document.spacial_fields_indexed.size == 1
primary = @document.spacial_fields_indexed.first
end
@opts[:calculate].each do |key|
res.geo[(key.to_s+'_distance').to_sym] = res.distance_from(key,center,{:unit =>@opts[:unit] || @opts[:distance_multiplier], :spherical => @opts[:spherical]} )
res.geo[:distance] = res.geo[key] if primary && key == primary
end
end
res
end
if @opts[:page]
start = (@opts[:page]-1)*@opts[:per_page] # assuming current_page is 1 based.
@_paginated_array = @_original_array.clone
super(@_paginated_array[@opts[:skip]+start, @opts[:per_page]] || [])
else
super(@_original_array[@opts[:skip]..-1] || [])
end
end
def page(*args)
new_collection = self.clone
new_collection.page!(*args)
new_collection
end
def page!(page, options = {})
original = options.delete(:original)
self.opts.merge!(options)
self.opts[:paginator] ||= Mongoid::Spacial.paginator
self.opts[:page] = page
start = (self.current_page-1)*self.limit_value # assuming current_page is 1 based.
if original
@_paginated_array = @_original_array.clone
self.replace(@_paginated_array[self.opts[:skip]+start, self.limit_value] || [])
else
@_paginated_array ||= self.to_a
self.replace(@_paginated_array[self.opts[:skip]+start, self.limit_value])
end
true
end
def per(num)
self.page(current_page, :per_page => num)
end
def reset!
self.replace(@_original_array)
@opts = @_original_opts
@_paginated_array = nil
true
end
def reset
clone = self.clone
clone.reset!
clone
end
def total_entries
(@_paginated_array) ? @_paginated_array.count : @_original_array.count
end
alias_method :total_count, :total_entries
def current_page
page = (@opts[:page]) ? @opts[:page].to_i.abs : 1
(page < 1) ? 1 : page
end
def limit_value
if @opts[:per_page]
@opts[:per_page] = @opts[:per_page].to_i.abs
else
@opts[:per_page] = case self.opts[:paginator]
when :will_paginate
@document.per_page
when :kaminari
Kaminari.config.default_per_page
else
Mongoid::Spacial.default_per_page
end
end
end
alias_method :per_page, :limit_value
def num_pages
(self.total_entries && @opts[:per_page]) ? self.total_entries/@opts[:per_page] : nil
end
alias_method :total_pages, :num_pages
def out_of_bounds?
self.current_page > self.total_pages
end
def offset
(self.current_page - 1) * self.per_page
end
# current_page - 1 or nil if there is no previous page
def previous_page
self.current_page > 1 ? (self.current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
self.current_page < self.total_pages ? (self.current_page + 1) : nil
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/spacial/document.rb | lib/mongoid_spacial/spacial/document.rb | module Mongoid
module Spacial
module Document
extend ActiveSupport::Concern
included do
attr_accessor :geo
cattr_accessor :spacial_fields, :spacial_fields_indexed
@@spacial_fields = []
@@spacial_fields_indexed = []
end
module ClassMethods #:nodoc:
# create spacial index for given field
# @param [String,Symbol] name
# @param [Hash] options options for spacial_index
def spacial_index name, *options
self.spacial_fields_indexed << name
index [[ name, ::Mongo::GEO2D ]], *options
end
end
def distance_from(key,p2, opts = {})
p1 = self.send(key)
Mongoid::Spacial.distance(p1, p2, opts)
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
ryanong/mongoid_spacial | https://github.com/ryanong/mongoid_spacial/blob/edb363054c4449892f4a0784ad9b826156af79a0/lib/mongoid_spacial/contexts/mongo.rb | lib/mongoid_spacial/contexts/mongo.rb | # encoding: utf-8
module Mongoid #:nodoc:
module Contexts #:nodoc:
class Mongo #:nodoc:
# Fetches rows from the data base sorted by distance.
# In MongoDB versions 1.7 and above it returns a distance.
# Uses all criteria chains except without, only, asc, desc, order_by
#
# @example Minimal Query
#
# Address.geo_near([70,40])
#
# @example Chained Query
#
# Address.where(:state => 'ny').geo_near([70,40])
#
# @example Calc Distances Query
#
# Address.geo_near([70,40], :max_distance => 5, :unit => 5)
#
# @param [ Array, Hash, #to_lng_lat ] center The center of where to calculate distance from
# @param [ Hash ] opts the options to query with
# @options opts [Integer] :num The number of rows to fetch
# @options opts [Hash] :query The query to filter the rows by, accepts
# @options opts [Numeric] :distance_multiplier this is multiplied against the calculated distance
# @options opts [Numeric] :max_distance The max distance of a row that should be returned in :unit(s)
# @options opts [Numeric, :km, :k, :mi, :ft] :unit automatically sets :distance_multiplier and converts :max_distance
# @options opts [true,false] :spherical Will determine the distance either by spherical calculation or flat calculation
# @options opts [TrueClass,Array<Symbol>] :calculate Which extra fields to calculate distance for in ruby, if set to TrueClass it will calculate all spacial fields
#
# @return [ Array ] Sorted Rows
def geo_near(center, opts = {})
opts = self.options.merge(opts)
# convert point
center = center.to_lng_lat if center.respond_to?(:to_lng_lat)
# set default opts
opts[:skip] ||= 0
if unit = Mongoid::Spacial.earth_radius[opts[:unit]]
opts[:unit] = (opts[:spherical]) ? unit : unit * Mongoid::Spacial::RAD_PER_DEG
end
if unit = Mongoid::Spacial.earth_radius[opts[:distance_multiplier]]
opts[:distance_multiplier] = (opts[:spherical]) ? unit : unit * Mongoid::Spacial::RAD_PER_DEG
end
opts[:distance_multiplier] = opts[:unit] if opts[:unit].kind_of?(Numeric)
# setup paging.
if opts.has_key?(:page)
opts[:page] ||= 1
opts[:paginator] ||= Mongoid::Spacial.paginator()
if opts[:per_page].blank?
opts[:per_page] = case opts[:paginator]
when :will_paginate
@document.per_page
when :kaminari
Kaminari.config.default_per_page
else
Mongoid::Spacial.default_per_page
end
opts[:per_page] = opts[:per_page].to_i
end
end
opts[:query] = create_geo_near_query(center,opts)
results = klass.db.command(opts[:query])
Mongoid::Spacial::GeoNearResults.new(klass,results,opts)
end
private
def create_geo_near_query(center,opts)
# minimum query
query = {
:geoNear => klass.collection_name,
:near => center,
}
# create limit and use skip
if opts[:num]
query['num'] = opts[:skip].to_i + opts[:num].to_i
elsif opts[:limit]
query['num'] = opts[:skip].to_i + opts[:limit].to_i
elsif opts[:page]
query['num'] = opts[:skip].to_i + (opts[:page].to_i * opts[:per_page].to_i)
end
# allow the use of complex werieis
if opts[:query]
query['query'] = self.criteria.where(opts[:query]).selector
elsif self.selector != {}
query['query'] = self.selector
end
if opts[:max_distance]
query['maxDistance'] = opts[:max_distance].to_f
query['maxDistance'] = query['maxDistance']/opts[:unit].to_f if opts[:unit]
end
if klass.db.connection.server_version >= '1.7'
query['spherical'] = true if opts[:spherical]
# mongodb < 1.7 returns degrees but with earth flat. in Mongodb 1.7 you can set sphere and let mongodb calculate the distance in Miles or KM
# for mongodb < 1.7 we need to run Haversine first before calculating degrees to Km or Miles. See below.
query['distanceMultiplier'] = opts[:distance_multiplier].to_f if opts[:distance_multiplier]
end
query
end
end
end
end
| ruby | MIT | edb363054c4449892f4a0784ad9b826156af79a0 | 2026-01-04T17:44:07.066009Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/place_serializer.rb | app/serializers/place_serializer.rb | class PlaceSerializer < ActiveModel::Serializer
attributes :id, :date, :lat, :lng
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/weight_serializer.rb | app/serializers/weight_serializer.rb | class WeightSerializer < ActiveModel::Serializer
attributes :id, :bmi, :value, :lean_mass, :fat_mass, :fat_percent, :date
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/user_serializer.rb | app/serializers/user_serializer.rb | class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :name, :height
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/journal_entry_serializer.rb | app/serializers/journal_entry_serializer.rb | class JournalEntrySerializer < ActiveModel::Serializer
attributes :id, :recorded_at, :feelings, :happiness, :strategies
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/meal_serializer.rb | app/serializers/meal_serializer.rb | class MealSerializer < ActiveModel::Serializer
attributes :id, :date, :calories, :carbohydrates, :fat, :protein,
:carbohydrates_percentage, :fat_percentage, :protein_percentage
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/serializers/sleep_serializer.rb | app/serializers/sleep_serializer.rb | class SleepSerializer < ActiveModel::Serializer
attributes :id, :start, :end, :user_id
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/helpers/dashboard_helper.rb | app/helpers/dashboard_helper.rb | module DashboardHelper
def domain_resize(user_data)
user_data.map do |d|
if d == user_data.min
0
elsif d == user_data.max
1
else
(d-user_data.min) * 1/(user_data.max-user_data.min).to_f
end
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/helpers/meals_helper.rb | app/helpers/meals_helper.rb | module MealsHelper
def macro_percent_for_meals meals, macro
sum = 0
Meal::MACRO_NUTRIENTS.each do |macro|
sum += meals.to_a.sum(¯o.to_sym)
end
meals.to_a.sum(¯o.to_sym).to_f / sum.to_f * 100
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/helpers/sleeps_helper.rb | app/helpers/sleeps_helper.rb | module SleepsHelper
def formatted_duration sleep
pluralize ( sleep.duration / 1.hour).round(1), 'hour'
end
def average_duration opts={}
opts = {
start: 7.days.ago.at_beginning_of_day,
end: Date.today.at_beginning_of_day
}.merge(opts)
sleeps = current_user.sleeps_between(opts[:start], opts[:end])
if sleeps.present?
( sleeps.map(&:duration).reduce(&:+) || 0 ) / sleeps.size
else
0
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def nav_link text, link, icon={}
icon = {
size: "1x"
}.merge(icon)
content = link_to icon[:type].present? ? fa_icon(icon[:type].to_s, text: text, class: icon[:size].to_s) : text, link
if current_page? link
content_tag :li, class: "active" do
content
end
else
content_tag(:li) do
content
end
end
end
def flash_class(level)
case level
when "notice" then "message-info"
when "success" then "message-success"
when "error" then "message-danger"
when "alert" then "message-danger"
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/extensions/models/users/weights.rb | app/extensions/models/users/weights.rb | module Users
module Weights
def current_weight opts={}
self.weights.current(:value, opts)
end
alias_method :weight, :current_weight
def fat_mass opts={}
self.weights.current(:fat_mass, opts)
end
def fat_percent opts={}
self.weights.current(:fat_percent, opts)
end
def lean_mass opts={}
self.weights.current(:lean_mass, opts)
end
def lean_mass_percentage
lean_mass / weight * 100
end
def bmi opts={}
self.weights.current(:bmi, opts)
end
protected
def update_weights_bmi
Weight.update_bmi_for_user(id)
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/extensions/models/users/meals.rb | app/extensions/models/users/meals.rb | module Users
module Meals
def meals_from datetime
meals.where("date >= ?", datetime)
end
def meals_after datetime
meals.where("date > ?", datetime)
end
def meals_before datetime
meals.where("date < ?", datetime)
end
def meals_on datetime
meals.where("date = ?", datetime)
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/extensions/models/users/sleeps.rb | app/extensions/models/users/sleeps.rb | module Users
module Sleeps
def sleeps_from datetime
sleeps.where('start >= ?', datetime)
end
def sleeps_between start_datetime, end_datetime
sleeps.where('start >= ? AND "end" <= ?', start_datetime, end_datetime)
end
def sleeps_after datetime
sleeps.where('start > ?', datetime)
end
def sleeps_before datetime
sleeps.where('start < ?', datetime)
end
def sleeps_on datetime
sleeps.where('start = ?', datetime)
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/meals_controller.rb | app/controllers/meals_controller.rb | class MealsController < ApplicationController
before_action :authenticate_user!
before_action :set_meal, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /meals
# GET /meals.json
def index
@meals = current_user.meals.order("date DESC")
respond_to do |format|
format.html do
@meals_grouped_by_date = @meals.group_by { |m| m.date }
end
format.json { render json: @meals }
end
end
# GET /meals/1
# GET /meals/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @meal }
end
end
# GET /meals/new
# GET /meals/new.json
def new
@meal = Meal.new
@meal.date = Date.current
respond_to do |format|
format.html # new.html.erb
format.json { render json: @meal }
end
end
# GET /meals/1/edit
def edit
end
# POST /meals
# POST /meals.json
def create
@meal = current_user.meals.new(meal_params)
respond_to do |format|
if @meal.save
format.html { redirect_to meals_path, notice: 'Meal was successfully created.' }
format.json { render json: @meal, status: :created, location: @meal }
else
format.html { render action: "new" }
format.json { render json: @meal.errors, status: :unprocessable_entity }
end
end
end
# PUT /meals/1
# PUT /meals/1.json
def update
respond_to do |format|
if @meal.update_attributes(meal_params)
format.html { redirect_to meals_path, notice: 'Meal was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @meal.errors, status: :unprocessable_entity }
end
end
end
# DELETE /meals/1
# DELETE /meals/1.json
def destroy
@meal.destroy
respond_to do |format|
format.html { redirect_to meals_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_meal
@meal = Meal.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def meal_params
params.require(:meal).permit(:date, :calories, :carbohydrates, :fat, :protein, :description)
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/home_controller.rb | app/controllers/home_controller.rb | class HomeController < ApplicationController
skip_authorization_check
# GET /home
def index
respond_to do |format|
format.html # index.html.erb
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/omniauth_callbacks_controller.rb | app/controllers/omniauth_callbacks_controller.rb | class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def failure
flash[:alert] = "There was an error connecting your accounts"
end
def withings
if user_signed_in?
if current_user.has_withings_auth?
flash[:success] = "You've already synchronized your scale"
else
current_user.create_withings_account(
userid: request.env["omniauth.auth"]["uid"],
oauth_token: request.env["omniauth.auth"]["credentials"]["token"],
oauth_token_secret: request.env["omniauth.auth"]["credentials"]["secret"]
)
flash[:success] = "Withings scale synchronized"
end
redirect_to dashboard_index_path
else
flash[:alert] = "You must be signed in to authenticate your Withings account"
redirect_to new_user_session_path
end
end
def fitbit
if user_signed_in?
if current_user.has_fitbit_auth?
flash[:success] = "You've already synchronized your Fitbit account"
else
current_user.create_fitbit_account(
uid: request.env["omniauth.auth"]["uid"],
oauth_token: request.env["omniauth.auth"]["credentials"]["token"],
oauth_token_secret: request.env["omniauth.auth"]["credentials"]["secret"],
activated_at: Date.parse(request.env["omniauth.auth"]["info"]["member_since"].to_s)
)
flash[:success] = "Fitbit account synchronized"
end
redirect_to dashboard_index_path
else
flash[:alert] = "You must be signed in to authenticate your Fitbit account"
redirect_to new_user_session_path
end
end
def foursquare
if user_signed_in?
if current_user.has_foursquare_auth?
flash[:success] = "You've already synchronized your Foursquare account"
else
current_user.create_foursquare_account(
uid: request.env["omniauth.auth"]["uid"],
oauth_token: request.env["omniauth.auth"]["credentials"]["token"],
activated_at: Time.at(request.env["omniauth.auth"]["extra"]["raw_info"]["createdAt"]).utc.to_datetime
)
flash[:success] = "Foursquare account synchronized"
end
redirect_to dashboard_index_path
else
flash[:alert] = "You must be signed in to authenticate your Foursquare account"
redirect_to new_user_session_path
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/journal_entries_controller.rb | app/controllers/journal_entries_controller.rb | class JournalEntriesController < ApplicationController
before_action :authenticate_user!
before_action :set_journal_entry, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /journal_entries
# GET /journal_entries.json
def index
@journal_entries = current_user.journal_entries
respond_to do |format|
format.html # show.html.erb
format.json { render json: @journal_entries }
end
end
# GET /journal_entries/1
# GET /journal_entries/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @journal_entry }
end
end
# GET /journal_entries/new
# GET /journal_entries/new.json
def new
@journal_entry = JournalEntry.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @journal_entry }
end
end
# GET /journal_entries/1/edit
def edit
end
# POST /journal_entries
# POST /journal_entries.json
def create
@journal_entry = current_user.journal_entries.new(journal_entry_params)
respond_to do |format|
if @journal_entry.save
format.html { redirect_to journal_entries_url, notice: 'journal_entry was successfully created.' }
format.json { render json: @journal_entry, status: :created, location: @journal_entry }
else
format.html { render action: 'new' }
format.json { render json: @journal_entry.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /journal_entries/1
# PATCH/PUT /journal_entries/1.json
def update
respond_to do |format|
if @journal_entry.update(journal_entry_params)
format.html { redirect_to journal_entries_url, notice: 'journal_entry was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @journal_entry.errors, status: :unprocessable_entity }
end
end
end
# DELETE /journal_entries/1
# DELETE /weights/1.json
def destroy
@journal_entry.destroy
respond_to do |format|
format.html { redirect_to journal_entries_url, notice: 'journal_entry was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_journal_entry
@journal_entry = journal_entry.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def journal_entry_params
params.require(:journal_entry).permit(:recorded_at, :feelings, :happiness, :strategies)
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/places_controller.rb | app/controllers/places_controller.rb | class PlacesController < ApplicationController
before_action :authenticate_user!
before_action :set_place, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /places
# GET /places.json
def index
@places = current_user.places.order("date DESC")
respond_to do |format|
format.html # index.html.erb
format.json { render json: @places }
end
end
# GET /places/1
# GET /places/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @place }
end
end
# GET /places/new
# GET /places/new.json
def new
@place = Place.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @place }
end
end
# GET /places/1/edit
def edit
end
# POST /places
# POST /places.json
def create
@place = current_user.places.new(place_params)
respond_to do |format|
if @place.save
format.html { redirect_to place_path(@place), notice: 'Place was successfully created.' }
format.json { render json: @place, status: :created, location: @place }
else
format.html { render action: "new" }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
# PUT /places/1
# PUT /places/1.json
def update
respond_to do |format|
if @place.update_attributes(place_params)
format.html { redirect_to place_path(@place), notice: 'Place was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
# DELETE /places/1
# DELETE /places/1.json
def destroy
@place.destroy
respond_to do |format|
format.html { redirect_to places_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_place
@place = Place.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def place_params
params.require(:place).permit(:date, :lat, :lng)
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/dashboard_controller.rb | app/controllers/dashboard_controller.rb | class DashboardController < ApplicationController
before_action :authenticate_user!
skip_authorization_check
# GET /dashboard
# GET /dashboard.json
def index
respond_to do |format|
format.html # index.html.erb
format.json
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/weights_controller.rb | app/controllers/weights_controller.rb | class WeightsController < ApplicationController
before_action :authenticate_user!
before_action :set_weight, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /weights
# GET /weights.json
def index
@weights = current_user.weights.order("date DESC")
respond_to do |format|
format.html # index.html.erb
format.json { render json: @weights }
end
end
# GET /weights/1
# GET /weights/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @weight }
end
end
# GET /weights/new
# GET /weights/new.json
def new
@weight = Weight.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @weight }
end
end
# GET /weights/1/edit
def edit
end
# POST /weights
# POST /weights.json
def create
@weight = current_user.weights.new(weight_params)
respond_to do |format|
if @weight.save
format.html { redirect_to weight_path(@weight), notice: 'Weight was successfully created.' }
format.json { render json: @weight, status: :created, location: @weight }
else
format.html { render action: "new" }
format.json { render json: @weight.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /weights/1
# PATCH/PUT /weights/1.json
def update
respond_to do |format|
if @weight.update_attributes(weight_params)
format.html { redirect_to weight_path(@weight), notice: 'Weight was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @weight.errors, status: :unprocessable_entity }
end
end
end
# DELETE /weights/1
# DELETE /weights/1.json
def destroy
@weight.destroy
respond_to do |format|
format.html { redirect_to weights_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_weight
@weight = Weight.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def weight_params
params.require(:weight).permit(:value, :date, :lean_mass, :fat_mass, :fat_percent, :source, :meta)
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/users_controller.rb | app/controllers/users_controller.rb | class UsersController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
# GET /users/:id
# GET /users/:id.json
def show
@user = User.find(params[:id])
begin
@user.sync_all_provider_data
flash[:notice] = "API sources refreshed."
rescue Exceptions::ApiError
flash[:alert] = "API error - please connected and reconnect."
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @user }
end
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/registrations_controller.rb | app/controllers/registrations_controller.rb | class RegistrationsController < Devise::RegistrationsController
# As suggested by https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password
def update
@user = User.find(current_user.id)
successfully_updated = if needs_password? @user, params
@user.update_with_password params[:user]
else
# remove the virtual current_password attribute update_without_password
# doesn't know how to ignore it
params[:user].delete :current_password
@user.update_without_password params[:user]
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
end
private
# check if we need password to update user data
# ie if password or email was changed
# extend this as needed
def needs_password?(user, params)
user.email != params[:user][:email] ||
!params[:user][:password].blank?
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
before_action :set_timezone
# Provides us with global authentication handling, by assuming that
# every non-devise controller requires authorization, and rescues from
# the case of an access denied error from CanCan (in the case of a
# user requesting access to someone else's resource, for example)
check_authorization :unless => :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
redirect_to "/", :alert => exception.message
end
def set_timezone
Time.zone = current_user.time_zone if current_user
end
# Required by the strong params behavior in Rails 4.0
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/controllers/sleeps_controller.rb | app/controllers/sleeps_controller.rb | class SleepsController < ApplicationController
before_action :authenticate_user!
before_action :set_sleep, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /sleeps
# GET /sleeps.json
def index
@sleeps = current_user.sleeps.order("start DESC")
respond_to do |format|
format.html # show.html.erb
format.json { render json: @sleeps }
end
end
# GET /sleeps/1
# GET /sleeps/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @sleep }
end
end
# GET /sleeps/new
# GET /sleeps/new.json
def new
@sleep = Sleep.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @sleep }
end
end
# GET /sleeps/1/edit
def edit
end
# POST /sleeps
# POST /sleeps.json
def create
@sleep = current_user.sleeps.new(sleep_params)
respond_to do |format|
if @sleep.save
format.html { redirect_to sleeps_url, notice: 'Sleep was successfully created.' }
format.json { render json: @sleep, status: :created, location: @sleep }
else
format.html { render action: 'new' }
format.json { render json: @sleep.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /sleeps/1
# PATCH/PUT /sleeps/1.json
def update
respond_to do |format|
if @sleep.update(sleep_params)
format.html { redirect_to sleeps_url, notice: 'Sleep was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @sleep.errors, status: :unprocessable_entity }
end
end
end
# DELETE /sleeps/1
# DELETE /weights/1.json
def destroy
@sleep.destroy
respond_to do |format|
format.html { redirect_to sleeps_url, notice: 'Sleep was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_sleep
@sleep = Sleep.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def sleep_params
params.require(:sleep).permit(:start, :end)
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/models/place.rb | app/models/place.rb | # == Schema Information
#
# Table name: places
#
# id :integer not null, primary key
# user_id :integer
# date :datetime
# lat :decimal(, )
# lng :decimal(, )
# created_at :datetime
# updated_at :datetime
# meta :hstore
# source :string(255)
# response :json
#
class Place < ActiveRecord::Base
acts_as_geolocated
belongs_to :user
validates :date, presence: true
validates :lat, presence: true, numericality: true
validates :lng, presence: true, numericality: true
attr_accessible :date, :lat, :lng, :response, :source, :meta
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
jdjkelly/quant | https://github.com/jdjkelly/quant/blob/b3a1d83466ff5bb3b80e29f4d9999d871c77d280/app/models/ability.rb | app/models/ability.rb | class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
alias_action :create, :read, :update, :destroy, :to => :crud
can :crud, :all, :user_id => user.id
end
end
| ruby | MIT | b3a1d83466ff5bb3b80e29f4d9999d871c77d280 | 2026-01-04T17:44:17.025352Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.