Module: SimplyStored::Couch::HasOne

Included in:
ClassMethods
Defined in:
lib/simply_stored/couch/has_one.rb

Defined Under Namespace

Classes: Property

Instance Method Summary collapse

Instance Method Details

#define_has_one_getter(name, options) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/simply_stored/couch/has_one.rb', line 34

def define_has_one_getter(name, options)
  define_method(name) do |*args|
    local_options = args.first && args.first.is_a?(Hash) && args.first
    forced_reload, with_deleted, limit, descending = extract_association_options(local_options)

    if forced_reload || instance_variable_get("@#{name}").nil?
      found_object = find_one_associated(options[:class_name], self.class, :with_deleted => with_deleted, :foreign_key => options[:foreign_key])
      instance_variable_set("@#{name}", found_object)
      self.class.set_parent_has_one_association_object(self, found_object)
    end
    instance_variable_get("@#{name}")
  end
end

#define_has_one_setter(name, options) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/simply_stored/couch/has_one.rb', line 9

def define_has_one_setter(name, options)
  define_method("#{name}=") do |value|
    klass = self.class.get_class_from_name(self.class._find_property(name).options[:class_name])
    raise ArgumentError, "expected #{klass} got #{value.class}" unless value.nil? || value.is_a?(klass)
    old_value = send("#{name}", :force_reload => true)
    if value.nil?
      instance_variable_set("@#{name}", nil)
    else
      instance_variable_set("@#{name}", value)
      value.send("#{self.class.foreign_key}=", id)
      value.save
    end
    
    if old_value
      if options[:dependent] == :destroy
        old_value.destroy
      else
        old_value.send("#{self.class.foreign_property}=", nil)
        old_value.save
      end
    end
    old_value
  end
end

#has_one(name, options = {}) ⇒ Object



4
5
6
7
# File 'lib/simply_stored/couch/has_one.rb', line 4

def has_one(name, options = {})
  check_existing_properties(name, SimplyStored::Couch::HasOne::Property)
  properties << SimplyStored::Couch::HasOne::Property.new(self, name, options)
end

#set_parent_has_one_association_object(parent, child) ⇒ Object



48
49
50
51
52
# File 'lib/simply_stored/couch/has_one.rb', line 48

def set_parent_has_one_association_object(parent, child)
  if child.respond_to?("#{parent.class.name.to_s.singularize.downcase}=")
    child.send("#{parent.class.name.to_s.singularize.camelize.downcase}=", parent)
  end
end