Skip to content

Instantly share code, notes, and snippets.

@tomclose
Forked from jopotts/lookups.rb
Last active December 27, 2015 06:59
Show Gist options
  • Save tomclose/7285113 to your computer and use it in GitHub Desktop.
Save tomclose/7285113 to your computer and use it in GitHub Desktop.
module Lookups
# Allows the definition of lookup values in a class.
def define_lookup(klass_name, lookup_codes)
# Ensure the classname conforms to convention
klass_name = klass_name.to_s.classify
# Add class methods
klass = Class.new do
cattr_accessor :codes
# Allow access using LookupName.code(:the_code)
def self.code(code)
send(code.to_s)
end
# Get the translation for the code
def self.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 self.select_list
codes.map { |code| [human_name(code), code] }
end
# Check that the given type exists
def self.valid_type?(code)
codes.include?(code.to_s)
end
# Allow the use of LookupName.lookup_code (for example)
def self.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 self.respond_to?(method)
return true if valid_type?(method)
super
end
end
# Assign the class to its name
self.const_set(klass_name, c)
# Set the codes
klass.codes = lookup_codes
end
end
# Usage example
class FooBlah
extend Lookups
# To define a lookup
define_lookup "RecurrenceType", %w(minutely hourly daily weekly monthly yearly)
define_lookup "RepeatUntilType", %w(forever to_date occurrence_count)
def something
puts RecurrenceType.weekly
# Or
puts RecurrenceType.code(:weekly)
# Or referencing from outside the class
puts FooBlah::RecurrenceType.weekly
end
...
end
# To use in all AR classes, put in an initializer:
ActiveRecord::Base.extend Lookups
# In forms it can be used in select lists like this:
<%= f.select :recurrence_type, FooBlah::RecurrenceType.select_list %>
@jopotts
Copy link

jopotts commented Nov 3, 2013

Thanks Tom. I've reviewed mine and changed to a module now. The original was a mess!

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