Permalink
Browse files

- added first version of ActiveResource has_one associaion method

  • Loading branch information...
1 parent 7d3da5b commit 1cbff55cf84b61083d7d7cc6087036b1104c30e5 @gramos committed Sep 27, 2010
View
27 activeresource/lib/active_resource/associations.rb
@@ -1,7 +1,34 @@
module ActiveResource
module Associations
+ def hash_options(association, resource)
+ h = { :klass => klass_for(association, resource) }
+ h[:host_klass] = self
+ h[:association_col] = "#{h[:host_klass].to_s.downcase}_id".to_sym
+ h
+ end
+
+ def klass_for(association, resource)
+ resource = resource.to_s
+ resource = resource.singularize if association == :has_many
+ resource.camelize.constantize
+ end
+
def has_one(resource, opts = {})
+ h = hash_options(:has_one, resource)
+ klass_name = opts[:class_name].nil? ? resource : opts[:class_name]
+
+ #----------------------------------------------------------------------#
+ # Define accessor method for resource
+ #
+ #----------------------------------------------------------------------#
+ define_method(klass_name) do
+ if instance_variable_get("@#{resource}").nil?
+ instance_variable_set("@#{resource}",
+ h[:klass].find(:params => { h[:association_col] => id }) )
+ end
+ return instance_variable_get("@#{resource}")
+ end
end
end
View
7 activeresource/test/cases/associations_test.rb
@@ -1,6 +1,13 @@
require 'abstract_unit'
require "fixtures/project"
+class ProjectManager < ActiveResource::Base
+end
+
+class Project < ActiveResource::Base
+ has_one :project_manager
+end
+
class AssociationsTest < Test::Unit::TestCase
def setup
View
5 activeresource/test/fixtures/project.rb
@@ -3,11 +3,6 @@ class Project < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
#----------------------------------------------------------------------
- # associations
- #
- has_one :project_manager
-
- #----------------------------------------------------------------------
# validations
#
validates_presence_of :name

0 comments on commit 1cbff55

Please sign in to comment.