module DynamicModels
Public Instance Methods
base_model_class()
click to toggle source
# File lib/dynamic_models.rb, line 30 def base_model_class base_model_class_name.camelize.constantize end
base_model_class_name()
click to toggle source
the model class, inferred from the controller
# File lib/dynamic_models.rb, line 26 def base_model_class_name params[:controller].split('/').last.singularize end
fetch_model()
click to toggle source
returns a model using the id from the params
# File lib/dynamic_models.rb, line 60 def fetch_model model_class.find params[:id] end
fetch_model_list()
click to toggle source
returns an array of models (using the name of this controller)
# File lib/dynamic_models.rb, line 65 def fetch_model_list if parent_model return parent_model.send("#{model_name.pluralize.downcase}") else return model_class.find(:all) end end
model_class()
click to toggle source
the class we are working with, if an STI model then it will fail loudly on a type which inst descendant from the class which corresponds to this controller
# File lib/dynamic_models.rb, line 35 def model_class klass = model_name.camelize.constantize if sti_model? raise "you can only pass a type which descends from #{params[:controller]}" unless klass.sti_model? and klass.superclass == base_model_class end klass end
model_name()
click to toggle source
model name from the controller or type parameter (for a model which is using STI)
# File lib/dynamic_models.rb, line 21 def model_name sti_model? ? params[:type].underscore : base_model_class_name end
new_model(defaults = {})
click to toggle source
returns a new model, it can be set with an optional hash
# File lib/dynamic_models.rb, line 49 def new_model(defaults = {}) new_model = model_class.new(defaults) # if there is a parent then associate it with the model if parent_model new_model.send("#{parent_model.class.name.underscore}=", parent_model) end # return the new model new_model end
parent_model()
click to toggle source
looks for object_id notation, and returns a new model
# File lib/dynamic_models.rb, line 6 def parent_model params.each do |name, value| if name =~ /(.+)_id$/ return @parent_model ||= $1.camelize.constantize.find(value) end end nil end
plural_model_name()
click to toggle source
plural form of the model name from the controller
# File lib/dynamic_models.rb, line 44 def plural_model_name params[:controller].split('/').last end
sti_model?()
click to toggle source
if we are using a type parameter, then we are dealing with an STI model
# File lib/dynamic_models.rb, line 16 def sti_model? params[:type].present? end