2010-05-17 20:46:41 +00:00
|
|
|
class AssetField
|
|
|
|
include Mongoid::Document
|
|
|
|
include Mongoid::Timestamps
|
|
|
|
|
|
|
|
## fields ##
|
|
|
|
field :label, :type => String
|
|
|
|
field :_alias, :type => String # need it for instance in: > asset.description (description being a custom field)
|
|
|
|
field :_name, :type => String
|
|
|
|
field :kind, :type => String
|
|
|
|
field :position, :type => Integer, :default => 0
|
2010-05-17 22:51:53 +00:00
|
|
|
|
2010-05-17 20:46:41 +00:00
|
|
|
## validations ##
|
|
|
|
validates_presence_of :label, :kind
|
|
|
|
|
2010-05-19 16:17:45 +00:00
|
|
|
embedded_in :asset_collection, :inverse_of => :asset_fields
|
|
|
|
|
2010-05-17 20:46:41 +00:00
|
|
|
## methods ##
|
|
|
|
|
|
|
|
def field_type
|
|
|
|
case self.kind
|
|
|
|
when 'String', 'Text', 'Email' then String
|
|
|
|
else
|
|
|
|
self.kind.constantize
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def apply(object, association_name)
|
2010-05-17 22:51:53 +00:00
|
|
|
# puts "applying...#{self._name} / #{self._alias}"
|
2010-05-17 20:46:41 +00:00
|
|
|
object.class.send(:set_field, self._name, { :type => self.field_type })
|
|
|
|
object.class_eval <<-EOF
|
2010-05-17 22:51:53 +00:00
|
|
|
alias :#{self.safe_alias} :#{self._name}
|
|
|
|
alias :#{self.safe_alias}= :#{self._name}=
|
2010-05-17 20:46:41 +00:00
|
|
|
EOF
|
|
|
|
end
|
|
|
|
|
2010-05-17 22:51:53 +00:00
|
|
|
def safe_alias
|
|
|
|
self.set_alias
|
|
|
|
self._alias
|
|
|
|
end
|
2010-05-17 20:46:41 +00:00
|
|
|
|
2010-05-17 22:51:53 +00:00
|
|
|
protected
|
2010-05-17 20:46:41 +00:00
|
|
|
|
|
|
|
def set_unique_name!
|
|
|
|
self._name = "custom_field_#{self.increment_counter!}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_alias
|
|
|
|
return if self.label.blank? && self._alias.blank?
|
|
|
|
self._alias ||= self.label.clone
|
|
|
|
self._alias.slugify!(:downcase => true, :underscore => true)
|
|
|
|
end
|
|
|
|
|
|
|
|
def increment_counter!
|
2010-05-19 16:17:45 +00:00
|
|
|
next_value = (self._parent.send(:"#{self.association_name}_counter") || 0) + 1
|
2010-05-17 20:46:41 +00:00
|
|
|
self._parent.send(:"#{self.association_name}_counter=", next_value)
|
|
|
|
next_value
|
|
|
|
end
|
|
|
|
|
|
|
|
def siblings
|
|
|
|
self._parent.associations[self.association_name]
|
|
|
|
end
|
|
|
|
end
|