Skip to content

Instantly share code, notes, and snippets.

@digitalpardoe
Created July 16, 2011 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalpardoe/1086755 to your computer and use it in GitHub Desktop.
Save digitalpardoe/1086755 to your computer and use it in GitHub Desktop.
Caching Your Photographs
<% cache do %>
... Your view code here. ...
<% end %>
"#{RAILS_ROOT}/public/images/flickr_cache/small/"
"#{RAILS_ROOT}/public/images/flickr_cache/large/"
private
def check_cache
if ENV['RAILS_ENV'] == 'production'
flickr = Flickr.new(RAILS_ROOT + "/config/flickr.cache", FLICKR_API_KEY, FLICKR_SHARED_SECRET)
@photos = flickr.people.getPublicPhotos(flickr.people.findByUsername(FLICKR_USERNAME))
@db_photos = Array.new
Photo.find(:all).each { |p| @db_photos.push(p.flickr_id) }
for photo in @photos.reverse
if !@db_photos.include?(photo.id)
db_photo = Photo.new
db_photo.flickr_id = photo.id.to_i
db_photo.title = photo.flickr.photos.getInfo(photo.id).title
db_photo.description = photo.flickr.photos.getInfo(photo.id).description
db_photo.url = photo.flickr.photos.getInfo(photo.id).urls.values[0]
db_photo.save
open(File.expand_path("#{RAILS_ROOT}/public/images/flickr_cache/small/" + photo.id + ".jpg"),"w").write(open(photo.url('s')).read)
open(File.expand_path("#{RAILS_ROOT}/public/images/flickr_cache/large/" + photo.id + ".jpg"),"w").write(open(photo.url).read)
end
end
end
end
def view
unless read_fragment({})
check_cache
@photos = Photo.find(:all)
end
end
cd /your/rails/application
./script/generate model Photo
class CreatePhotos < ActiveRecord::Migration
def self.up
create_table :photos, :id => false do |t|
t.column "flickr_id", :string, :limit => 25, :null => false
t.column "title", :string, :limit => 250
t.column "description", :text
t.column "url", :string, :limit => 250
end
add_index :photos, :flickr_id
end
def self.down
drop_table :photos
end
end
<% for photo in @photos.reverse %>
<%= image_tag("/images/flickr_cache/small/" + photo.flickr_id + ".jpg", :alt => photo.title) %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment