Created
August 9, 2009 23:03
-
-
Save baldwindavid/164937 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'active_hash' | |
### HAS_MANY AND BELONGS_TO | |
module ActiveHash | |
class Base | |
class << self | |
def has_many(association_id, options = {}) | |
define_method(association_id) do | |
options = { | |
:class_name => association_id.to_s.classify, | |
:foreign_key => self.class.to_s.foreign_key | |
}.merge(options) | |
# all needs to be called prior to dynamic finders being available | |
options[:class_name].constantize.all | |
options[:class_name].constantize.send("find_all_by_#{options[:foreign_key]}", id) | |
end | |
end | |
def belongs_to(association_id, options = {}) | |
define_method(association_id) do | |
options = { | |
:class_name => association_id.to_s.classify, | |
:foreign_key => association_id.to_s.foreign_key | |
}.merge(options) | |
options[:class_name].constantize.find(send(options[:foreign_key])) | |
end | |
end | |
end | |
end | |
end | |
### CLASSES | |
class Country < ActiveHash::Base | |
self.data = [ | |
{:id => 1, :name => "US"}, | |
{:id => 2, :name => "Canada"} | |
] | |
has_many :states | |
has_many :provinces, :class_name => "State" | |
end | |
class State < ActiveHash::Base | |
self.data = [ | |
{:id => 1, :name => "California", :country_id => 1}, | |
{:id => 2, :name => "Alaska", :country_id => 1}, | |
{:id => 3, :name => "Iowa", :country_id => 1}, | |
{:id => 4, :name => "British Columbia", :country_id => 2}, | |
{:id => 5, :name => "Ontario", :country_id => 2} | |
] | |
belongs_to :country | |
end | |
### ACTIONS | |
get '/has_many' do | |
Country.last.provinces.inspect | |
end | |
get '/belongs_to' do | |
State.last.country.inspect | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment