Skip to content

Instantly share code, notes, and snippets.

@mlt
Last active July 2, 2020 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlt/7516848d3b133083d8c388ed4720eab0 to your computer and use it in GitHub Desktop.
Save mlt/7516848d3b133083d8c388ed4720eab0 to your computer and use it in GitHub Desktop.
A Rails mixin to make inquiries with lookup tables, e.g. when used in association
# Mix this into an AR class for lookup tables to perform an inquiry.
# For example, if Movie has Genre and genres table has id->genre mapping
# then one could use the_movie.genre.comedy? instead of the_movie.genre.genre == 'comedy'
module LookupTable
def self.included(base)
raise "#{name} can only be included into classes that inherit from ActiveRecord::Base, #{base.name} does not." unless base < ActiveRecord::Base
base.instance_variable_set :@lookup_column, base.name.demodulize.underscore
base.extend(ClassMethods)
end
module ClassMethods
attr_reader :lookup_column
# Reverse find
def rfind(value)
where(lookup_column => value).take
end
end
private
def respond_to_missing?(method_name, include_private = false)
(method_name[-1] == "?") || super
end
def method_missing(method_name, *arguments)
if method_name.to_s[-1, 1] == "?"
val = read_attribute self.class.lookup_column
val == method_name.to_s[0..-2]
else
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment