Skip to content

Instantly share code, notes, and snippets.

@shqear93
Last active February 26, 2023 21:19
Show Gist options
  • Save shqear93/4b07153b4ca7e4e4a41da492679f6c0e to your computer and use it in GitHub Desktop.
Save shqear93/4b07153b4ca7e4e4a41da492679f6c0e to your computer and use it in GitHub Desktop.
Use geocoder gem with database
# db/migrate/xxxxxxxxx_create_geocoder_data.rb
class CreateGeocoderData < ActiveRecord::Migration[6.0]
def change
create_table :geocoder_data, id: false do |t|
t.string :url, null: false, primary_key: true
t.jsonb :data
t.timestamps
end
end
end
# config/initializers/geocoder.rb
Geocoder.configure(
lookup: :google,
api_key: ENV['PLAECS_KEY'].try(:freeze),
cache: GeocoderDatum,
cache_prefix: false,
use_https: true
)
# app/models/geocoder_datum.rb
class GeocoderDatum < ApplicationRecord
serialize :data, Serializers::IndifferentHash
class << self
def [](url)
find_by_url(url)&.data_before_type_cast
end
def []=(url, value)
where(url: url).first_or_create(data: value).update(data: value)
end
def keys
pluck(:url)
end
end
end
class MyIndifferentHash < HashWithIndifferentAccess
def self.load(value)
HashWithIndifferentAccess.new(value)
end
def self.dump(obj)
obj = JSON.parse(obj) if obj.is_a?(String) rescue nil
obj.to_hash.with_indifferent_access rescue {}
end
end
@shqear93
Copy link
Author

This is an example of how to use geocoder with activerecord model instead of caching on redis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment