Module: Stonean::ClassyInheritance::ClassMethods

Defined in:
lib/classy-inheritance.rb

Instance Method Summary collapse

Instance Method Details

#can_be(model_sym, options = {}) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/classy-inheritance.rb', line 170

def can_be(model_sym, options = {})
  unless options[:as]
    raise ArgumentError, ":as attribute required when calling can_be"
  end

  klass = model_sym.to_s.classify

  define_method "is_a_#{model_sym}?" do
    eval("self.#{options[:as]}_type == '#{klass}'")
  end

  find_with_method = "find_with_#{self.name.underscore}"

  define_method "as_a_#{model_sym}" do
    eval("#{klass}.send(:#{find_with_method},self.#{options[:as]}_id)")
  end
end

#depends_on(model_sym, options = {}) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/classy-inheritance.rb', line 133

def depends_on(model_sym, options = {}) 
  define_relationship(model_sym,options)

  # Optional presence of handling
  if options.has_key?(:validates_presence_if) && options[:validates_presence_if] != true
    if [Symbol, String, Proc].include?(options[:validates_presence_if].class)
      validates_presence_of model_sym, :if => options[:validates_presence_if]
    end
  else
    validates_presence_of model_sym
  end

  if options.has_key?(:validates_associated_if) && options[:validates_associated_if] != true
    if [Symbol, String, Proc].include?(options[:validates_associated_if].class)
      validates_associated_dependent model_sym, options, :if => options[:validates_associated_if]
    end
  else
    validates_associated_dependent model_sym, options 
  end

  # Before save functionality to create/update the requisite object
  define_save_method(model_sym, options[:as]) unless options[:autosave]

  # Adds a find_with_<model_sym> class method
  define_find_with_method(model_sym)

  if options[:as]
    define_can_be_method_on_requisite_class(options[:class_name] || model_sym.to_s.classify, options[:as])
  end

  options[:attrs].each{|attr| define_accessors(model_sym, attr, options)}
end

#has_dependency(model_sym, options = {}) ⇒ Object



166
167
168
# File 'lib/classy-inheritance.rb', line 166

def has_dependency(model_sym, options = {})
  depends_on(model_sym, options.update(:has_dependency => true))
end