Skip to content

Instantly share code, notes, and snippets.

@jopotts
Last active December 26, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jopotts/7138478 to your computer and use it in GitHub Desktop.
Save jopotts/7138478 to your computer and use it in GitHub Desktop.
A module for the definition of lookup lists
require "active_support/inflector"
module Lookups
# Allows the definition of lookup values
def define_lookup(const_name, lookup_codes)
mod = Module.new do
extend self
@codes = lookup_codes
def codes
@codes
end
# Allow access using LookupName.code(:the_code)
def code(code)
send(code.to_s)
end
# Get the translation for the code
def human_name(code)
class_names = name.gsub('::','.').underscore
I18n.t("lookups.#{class_names}.#{code}")
end
# All of the types for use in a form select list
def select_list
@codes.map { |code| [human_name(code), code] }
end
# Check that the given type exists
def valid_type?(code)
@codes.include?(code.to_s)
end
# Allow the use of LookupName.lookup_code (for example)
def method_missing(method, *args, &block)
return method.to_s if valid_type?(method)
super
end
# Always have a respond_to with a method missing!
def respond_to?(method)
return true if valid_type?(method)
super
end
end
# Assign the module to its name
const_set(const_name, mod)
end
end
# Example
I18n.backend.store_translations('en', { lookups: { stall: { fruits: { apple: "Apple", orange: "Orange" } } } })
class Stall
extend Lookups
define_lookup "Fruits", %w(apple orange)
end
# Test
require "test/unit"
class TestLookups < Test::Unit::TestCase
def test_lookup
assert_equal("apple", Stall::Fruits.apple)
end
def test_lookup_by_code
assert_equal("apple", Stall::Fruits.code(:apple))
end
def test_human_name
assert_equal("Apple", Stall::Fruits.human_name(:apple))
end
def test_select_list
list = [["Apple", "apple"], ["Orange", "orange"]]
assert_equal(list, Stall::Fruits.select_list)
end
end
# In forms it can be used in select lists like this:
# <%= f.select :fruits, Stall::Fruits.select_list %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment