Module: AutoARRefrection

Defined in:
lib/auto_ar.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/auto_ar.rb', line 32

def self.included(base)
  base.class_eval do
    unless defined? method_missing_without_auto_ar
      alias_method_chain :method_missing, :auto_ar
    end
  end
end

Instance Method Details

#foo(parent_class, child_class) ⇒ Object



74
75
76
77
# File 'lib/auto_ar.rb', line 74

def foo(parent_class, child_class)
  parent_class.class_eval("has_many :#{child_class.to_s.pluralize.underscore}")
  child_class.class_eval("belongs_to :#{parent_class.to_s.singularize.underscore}")
end

#method_missing_with_auto_ar(method_sym, *args) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/auto_ar.rb', line 40

def method_missing_with_auto_ar(method_sym, *args)
  begin
    method_missing_without_auto_ar(method_sym, *args)
  rescue NoMethodError => e
    method_name = method_sym.to_s
    if method_name == method_name.singularize
      f_key = method_name.singularize.foreign_key
      if self.respond_to?(f_key)
        target_klass = Object.const_get(method_name.classify)
#            target_klass.class_eval("has_many :#{self.class.to_s.pluralize.underscore.intern}")
#            self.class.class_eval("belongs_to :#{method_sym}")
        foo(target_klass, self.class)
      else
        raise NoMethodError
      end
    elsif method_name == method_name.pluralize
      table_name = method_name.tableize
      f_key = self.class.to_s.foreign_key
      conn = self.connection
      if conn.tables.include?(table_name) &&
          conn.columns(table_name).map(&:name).include?(f_key)
        target_klass = Object.const_get(method_name.classify)
        target_klass.class_eval("belongs_to :#{self.class.to_s.singularize.underscore.intern}")
        self.class.class_eval("has_many :#{method_sym}")
      else
        raise NoMethodError
      end
    else
      raise NoMethodError
    end
    self.send(method_sym, *args)
  end
end