Commit ec70c6db by ivan Lan

Add module MediaColumn

parent b7c1b68b
module Whaleback
module MediaColumn
extend ActiveSupport::Concern
included do
end
class_methods do
def media_url_column column, column_parse=Proc.new(&:itself)
collection = "#{column}_attachments"
has_many collection.to_sym, ->{ where(column_name: column) }, class_name: 'Whaleback::Media::Attachment', as: :attached, dependent: :destroy
after_save {
refresh_attachments(column_parse.call(send(column)), column) if "saved_change_to_#{column}?".to_sym
}
end
def media_url_columns *columns
columns.each { |column| media_url_column(column) }
end
def rich_text_column column
media_url_column column, Proc.new { |val|
Nokogiri::HTML(val).xpath('//img').map { |ele| ele.attr('src') }
}
end
def rich_text_columns *columns
columns.each { |column| rich_text_column(column) }
end
end
def create_attachments urls, column_name
Array(urls).each do |url|
match = url.to_s.match(/^.*files\/(\d{3})\/(\d{3})\/(\d{3})/)
Whaleback::Media::Attachment.create!(
column_name: column_name,
attached: self,
obj_id: match[1..3].join
) if match
end
end
def ace_attachments column_name
Whaleback::Media::Attachment.where(
column_name: column_name,
attached: self,
).destroy_all
end
def refresh_attachments urls, column_name
ace_attachments column_name
create_attachments urls, column_name
end
end
end
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment