2011-10-30 23:02:41 +00:00
|
|
|
module Locomotive
|
|
|
|
class EditableFile < EditableElement
|
|
|
|
|
2012-03-21 23:50:34 +00:00
|
|
|
## behaviours ##
|
2012-03-08 01:32:59 +00:00
|
|
|
mount_uploader 'source', EditableFileUploader
|
2011-10-30 23:02:41 +00:00
|
|
|
|
2012-03-08 01:32:59 +00:00
|
|
|
replace_field 'source', ::String, true
|
2012-01-25 21:07:10 +00:00
|
|
|
|
2012-03-21 23:50:34 +00:00
|
|
|
## fields ##
|
2012-03-19 01:29:59 +00:00
|
|
|
field :default_source_url, :localize => true
|
|
|
|
|
2012-03-21 23:50:34 +00:00
|
|
|
## callbacks ##
|
2012-03-19 01:29:59 +00:00
|
|
|
after_save :propagate_content
|
|
|
|
|
|
|
|
## methods ##
|
|
|
|
|
|
|
|
# Returns the url or the path to the uploaded file
|
|
|
|
# if it exists. Otherwise returns the default url.
|
|
|
|
#
|
|
|
|
# @note This method is not used for the rendering, only for the back-office
|
|
|
|
#
|
|
|
|
# @return [String] The url or path of the file
|
|
|
|
#
|
2011-10-30 23:02:41 +00:00
|
|
|
def content
|
2012-03-19 01:29:59 +00:00
|
|
|
self.source? ? self.source.url : self.default_source_url
|
|
|
|
end
|
|
|
|
|
|
|
|
def default_content?
|
|
|
|
!self.source? && self.default_source_url.present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def copy_attributes(attributes)
|
|
|
|
unless self.default_content?
|
|
|
|
attributes.delete(:default_source_url)
|
|
|
|
end
|
|
|
|
|
|
|
|
super(attributes)
|
|
|
|
end
|
|
|
|
|
|
|
|
def copy_attributes_from(el)
|
|
|
|
super(el)
|
|
|
|
|
|
|
|
if el.source_translations.nil?
|
|
|
|
self.attributes['default_source_url'] = el.attributes['default_source_url'] || {}
|
|
|
|
else
|
|
|
|
el.source_translations.keys.each do |locale|
|
|
|
|
::Mongoid::Fields::I18n.with_locale(locale) do
|
|
|
|
self.default_source_url = el.source? ? el.source.url : el.default_source_url
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_source=(value)
|
|
|
|
self.source_will_change! # notify the page to run the callbacks for that element
|
|
|
|
self.default_source_url = nil
|
|
|
|
super
|
2011-10-30 23:02:41 +00:00
|
|
|
end
|
|
|
|
|
2011-11-21 01:27:05 +00:00
|
|
|
def as_json(options = {})
|
|
|
|
Locomotive::EditableFilePresenter.new(self).as_json
|
|
|
|
end
|
|
|
|
|
2012-03-19 01:29:59 +00:00
|
|
|
protected
|
|
|
|
|
|
|
|
def propagate_content
|
|
|
|
if self.source_changed?
|
|
|
|
operations = {
|
|
|
|
'$set' => {
|
|
|
|
"editable_elements.$.default_source_url.#{::Mongoid::Fields::I18n.locale}" => self.source.url
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.page.collection.update self._selector, operations, :multi => true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-10-30 23:02:41 +00:00
|
|
|
end
|
|
|
|
end
|