Last active
September 17, 2024 15:58
-
-
Save shqear93/4b07153b4ca7e4e4a41da492679f6c0e to your computer and use it in GitHub Desktop.
Use geocoder gem with database
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
# 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 |
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
# config/initializers/geocoder.rb | |
Geocoder.configure( | |
lookup: :google, | |
api_key: ENV['PLAECS_KEY'].try(:freeze), | |
cache: GeocoderDatum, | |
cache_prefix: false, | |
use_https: true | |
) |
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
# 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 |
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
class Serializers::IndifferentHash < 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of how to use geocoder with activerecord model instead of caching on redis