Skip to content

Instantly share code, notes, and snippets.

@rossmari
Created December 10, 2015 16:26
Show Gist options
  • Save rossmari/ee9bcb658da8a3fe8790 to your computer and use it in GitHub Desktop.
Save rossmari/ee9bcb658da8a3fe8790 to your computer and use it in GitHub Desktop.
another variation of constant loading with metaprogramming
module CountryStorage
private
# extend this module than call some constant
# using agreement COUNTRY_#{country_code}
# this will raise const_missing and than create constant COUNTRY_#{country_code}
# equal to Country.find_by(code: country_code)
# instead of using
# COUNTRY_ID = Country.find_by_code('US').id.freeze
# which may fall down your app if you trying to load unit when you don't have countries in DB
def const_missing(const_name)
country = nil
if const_name =~ /COUNTRY_(\S+)/
code = const_name.to_s.match(/COUNTRY_(\S+)/)[1]
country = set_country_const(const_name, code)
end
country || super
end
def set_country_const(name, code)
country = get_country(code)
if country
const_set(name , country)
end
return country
end
def get_country(code)
Country.find_by(code: code)
end
end
# class CountryStorageUser
# extend CountryStorage
#
# def initialize()
# us = COUNTRY_US
# ru = COUNTRY_RU
# us = COUNTRY_US
# end
#
# end
# === USAGE
# [1] pry(main)> CountryStorageUser.new
# Country Load (0.5ms) SELECT "countries".* FROM "countries" WHERE "countries"."code" = 'US' LIMIT 1
# Country Load (0.3ms) SELECT "countries".* FROM "countries" WHERE "countries"."code" = 'RU' LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment