Skip to content

Commit

Permalink
Merge pull request #1 from techbang/t7265
Browse files Browse the repository at this point in the history
相同路徑產生相同 CDN 數字,並修正 .tw 圖片沒有上 CDN 的問題
  • Loading branch information
Domon committed Jun 13, 2012
2 parents 2344a5c + 84b6608 commit 1f29dbb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
31 changes: 21 additions & 10 deletions lib/cdn_image_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,40 @@ class <<self

def render_with_cdn_images(text, size = :medium)
return text unless text.respond_to?(:gsub)
text.gsub(/(href|src)="(#{CdnImageHelper.app_url})?\/system\/images\/(\d+)\/(\w+)\//) do |match|
link_type, host, id, scale = $1, $2, $3, $4
cdn_host = CdnImageHelper.cdn_host % rand(4) if Rails.env.production?
new_size = link_type == "href" ? :original : size
%|#{link_type}="#{cdn_host}/system/images/#{id}/#{new_size}/|

escaped_app_url = Regexp.escape(CdnImageHelper.app_url)
text.gsub(/(href|src)="(#{escaped_app_url}(\.tw)?)?\/system\/images\/(\d+)\/(\w+)\//) do |match|
link_type, host, tw, id, scale = $1, $2, $3, $4, $5
new_size = (link_type == "href") ? :original : size
path = "/system/images/#{id}/#{new_size}/"
%|#{link_type}="#{Rails.env.production? ? cdn_url_for(path) : path}|
end
end

def render_with_cdn_excerpt_images(text, size = :medium)
return text unless text.respond_to?(:gsub)
text.gsub(/(#{CdnImageHelper.app_url})?\/system\/excerpt_images\/(\d+)\/(\w+)\//) do |match|
host, id, scale = $1, $2, $3
cdn_host = CdnImageHelper.cdn_host % rand(4) if Rails.env.production?
%|#{cdn_host}/system/excerpt_images/#{id}/#{size}/|

escaped_app_url = Regexp.escape(CdnImageHelper.app_url)
text.gsub(/(#{escaped_app_url}(\.tw)?)?\/system\/excerpt_images\/(\d+)\/(\w+)\//) do |match|
host, tw, id, scale = $1, $2, $3, $4
path = "/system/excerpt_images/#{id}/#{size}/"
Rails.env.production? ? cdn_url_for(path) : path
end
end

def replace_image_size(text, size = :medium)
return text unless text.respond_to?(:gsub)

text.gsub(/\/system\/images\/(\d+)\/(\w+)\//) do |match|
id, scale = $1, $2
%|/system/images/#{id}/#{size}/|
end
end

def cdn_url_for(path, cdn_host = CdnImageHelper.cdn_host)
cdn_number = Digest::MD5.hexdigest(path).to_i(16) % 4
cdn_host = cdn_host % cdn_number
"#{cdn_host}#{path}"
end

end
end
2 changes: 1 addition & 1 deletion lib/cdn_image_helper/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module CdnImageHelper
VERSION = "0.0.1"
VERSION = "0.0.2"
end

0 comments on commit 1f29dbb

Please sign in to comment.