Module: PolymorphicModel::ClassMethods
- Defined in:
- lib/polymorphic_model.rb
Instance Method Summary collapse
-
#define_type(t, options = {}) ⇒ Object
defines new type for model.
- #polymorphic_column_name ⇒ Object
-
#types ⇒ Object
Returns list of allowed model types.
-
#validates_type ⇒ Object
Type validation for polymorphic model.
Instance Method Details
#define_type(t, options = {}) ⇒ Object
defines new type for model
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/polymorphic_model.rb', line 53 def define_type(t, = {}) column = @_polymorphic_column @_model_types << t.to_sym define_method :"#{t.to_s}?" do send(column) == t.to_s end validates_type condition_hash = {column => t.to_s} if [:singleton] == true validates_uniqueness_of column, :if => :"#{t}?" self.class.instance_eval do define_method t do scope = scoped(:conditions => condition_hash) scope.first || ([:autocreate] ? create!(condition_hash) : scope) end end else named_scope(t, :conditions => condition_hash) end end |
#polymorphic_column_name ⇒ Object
35 36 37 |
# File 'lib/polymorphic_model.rb', line 35 def polymorphic_column_name @_polymorphic_column end |
#types ⇒ Object
Returns list of allowed model types
31 32 33 |
# File 'lib/polymorphic_model.rb', line 31 def types @_model_types.clone.freeze end |
#validates_type ⇒ Object
Type validation for polymorphic model
40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/polymorphic_model.rb', line 40 def validates_type validates_each @_polymorphic_column, {:on => :save} do |record, attr_name, value| unless value.nil? || value == "" unless self.types.include?(value.to_sym) record.errors.add_to_base("is undefined type (#{value.to_s}), correct types are: [#{self.types.map(&:to_s).join(', ')}]") end else record.errors.add_to_base("is not any type, correct types are: [#{self.types.map(&:to_s).join(', ')}]") end end end |