Module: CouchSurfer::Associations::ClassMethods

Defined in:
lib/couch_surfer/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(*args) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/couch_surfer/associations.rb', line 38

def belongs_to *args
  options = extract_options!(args)
  parent = args.first
  parent_name = (options[:class_name] || parent).to_s
  define_method parent do
    class_name = ::Extlib::Inflection.camelize(parent_name)
    klass = ::Extlib::Inflection.constantize(class_name)
    parent_id = self["#{parent_name}_id"]
    if parent_id
      klass.send(:get, self["#{parent_name}_id"])
    end
  end

  define_method "#{parent}=".to_sym do |parent_obj|
    self["#{parent_obj.class.name.downcase}_id"] = parent_obj.id
  end
end

#has_many(*args) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/couch_surfer/associations.rb', line 4

def has_many *args
  options = extract_options!(args)
  children = args.first
  if options[:inline]
    name =  ::Extlib::Inflection.camelize(children.to_s.singular)
    cast children, :as => [name]
    define_method children do |*args|
      kinder = self[children.to_s]
      klass = ::Extlib::Inflection.constantize(name)
      if kinder.kind_of?(Array)
        self[children.to_s] =  kinder.map{|c| klass.send(:new, c)} unless kinder.first.kind_of?(klass)
      else
        self[children.to_s] = []
      end
      self[children.to_s]
    end
    return
  end
  if options[:through]
    define_method_for_children(options[:through], options)
    define_method children do
      name = (options[:class_name] || children).to_s.singular
      class_name =  ::Extlib::Inflection.camelize(name)
      klass = ::Extlib::Inflection.constantize(class_name)
      through_items = self.send("#{options[:through]}")
      query ||= {:keys => through_items.map{|child| child.send("#{name}_id")}}
      view_name ||= "by_#{self.class.name.downcase}_id"
      klass.send("all", query)
    end
    return
  end
  define_method_for_children(children, options, options[:class_name])
end