Created
January 15, 2012 19:00
-
-
Save xenda/1616775 to your computer and use it in GitHub Desktop.
Testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#require 'open-uri' | |
class GoogleImage < ActiveRecord::Base | |
API_FIELDS = %w{lat lng size markers sensor zoom center format maptype language mobile} | |
API_URL = "http://maps.google.com/maps/api/staticmap?" | |
has_attached_file :image, :storage => :s3, :s3_credentials => "#{Rails.root.to_s}/config/s3.yml" | |
def self.send_image_for_params(params) | |
gi = GoogleImage.send(method_for_params(params),*arguments_for_params(params)) | |
gi.download_image unless gi.image_file_name | |
gi.image.url | |
end | |
def self.method_for_params(params) | |
base = "find_or_create_by_" | |
base += valid_params(params).keys.join("_and_") | |
base | |
end | |
def self.arguments_for_params(params) | |
valid_params(params).values.map{|i| i.gsub("|","%7C")} | |
end | |
def build_url | |
params = build_params | |
url_query = params_for_url(params) | |
"#{API_URL}#{url_query}".force_encoding("UTF-8") | |
end | |
def params_for_url(params) | |
params.join("&") | |
end | |
def self.valid_params(params) | |
params.select{|k,v| API_FIELDS.include? k.to_s } | |
end | |
def build_params | |
params = API_FIELDS.map do |field| | |
"#{field}=#{self.send(field)}" if self.send(field) | |
end | |
params.compact! | |
end | |
def download_image | |
puts build_url | |
logger.info build_url | |
self.image = URLTempfile.new(build_url) #open(build_url, 'User-Agent' => 'ruby') | |
self.save! | |
rescue Exception => ex | |
logger.info ex.message | |
logger.info ex.backtrace | |
end | |
# def self.build_from_params(params) | |
# API_FIELDS.each do |field| | |
# self.send("#{field}=",params[field]) if params[field] | |
# end | |
# end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment