Module: SupportSegment::StiHelpers::ClassMethods

Defined in:
lib/support_segment/sti_helpers.rb

Instance Method Summary collapse

Instance Method Details

#implied_inheritance_class(*inheritance_type_sources) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/support_segment/sti_helpers.rb', line 76

def implied_inheritance_class(*inheritance_type_sources)
  if scope_values = self.current_scope.try(:where_values_hash)
    inheritance_type_sources << scope_values
  end

  valid_sources = inheritance_type_sources.select do |source|
    source.is_a? Hash
  end

  inheritance_type = valid_sources.inject(nil) do |type, values|
     type ? type : values.with_indifferent_access[inheritance_column]
  end

  inheritance_type
end

#inherited(child) ⇒ Object



35
36
37
38
39
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
# File 'lib/support_segment/sti_helpers.rb', line 35

def inherited(child)
  super
  base = sti_base_class


  child.instance_eval do
    def self.sti_helpers_base
      false
    end

    def model_name
      sti_base_class.model_name
    end
  end

  method_name = :"#{child.name.to_s.demodulize.underscore.pluralize}"

  base.define_singleton_method method_name do
    where(inheritance_column.to_sym => child.name)
  end

  sti_association_extensions.send :define_method, method_name do
    relation = where(inheritance_column.to_sym => child.name)
    relation.define_singleton_method :build do |*args, &block|
      result = super(*args, &block)
      proxy_association.add_to_target(result)
    end
    
    relation
  end

end

#new(*a, &b) ⇒ Object

!! with the first conditional clause type logic will only apply to base class

this MAY not be what you'd want, in which case ommit.


94
95
96
97
98
99
100
101
102
# File 'lib/support_segment/sti_helpers.rb', line 94

def new(*a, &b)
  if (self == sti_base_class) \
  and (subclass_name = implied_inheritance_class(a.first)) \
  and (subclass = subclass_name.safe_constantize) != self
    raise "wtF hax!!"  unless subclass < self  # klass should be a descendant of us
    return subclass.new(*a, &b)
  end
  super(*a, &b)
end

#select_optionsObject



23
24
25
# File 'lib/support_segment/sti_helpers.rb', line 23

def select_options
  descendants.map{ |c| c.to_s }.sort
end

#sti_association_extensionsObject



31
32
33
# File 'lib/support_segment/sti_helpers.rb', line 31

def sti_association_extensions
  @sti_association_extensions ||= Module.new
end

#sti_base_classObject



68
69
70
71
72
73
74
# File 'lib/support_segment/sti_helpers.rb', line 68

def sti_base_class
  # TODO: use the included hook to set the sti_base_class class?
  if self.sti_helpers_base
    return self
  end
  return superclass.sti_base_class
end

#sti_helpers_baseObject



27
28
29
# File 'lib/support_segment/sti_helpers.rb', line 27

def sti_helpers_base
  true
end