Skip to content

Instantly share code, notes, and snippets.

@jhchabran
Created September 24, 2009 20:28
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 jhchabran/193034 to your computer and use it in GitHub Desktop.
Save jhchabran/193034 to your computer and use it in GitHub Desktop.
module Keywordable
module ClassMethods
def keyword(symbol, proc)
write_inheritable_attribute :keywords, {} unless read_inheritable_attribute :keywords
read_inheritable_attribute(:keywords)[symbol] = proc
end
end
module InstanceMethods
def keywords
self.class.read_inheritable_attribute(:keywords)
end
def to_keywords
returning({}) do |h|
keywords.each do |keyword, proc|
h[keyword] = proc.call(self)
end
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
# class Program < ActiveRecord::Base
# include Keywordable
#
# belongs_to :city, :include => :county
#
# keyword :city, Proc.new { |program| program.city.name }
# keyword :county, Proc.new { |program| program.city.county.name }
# end
# Program.first.to_keywords
# => {:city=>"ANSE BERTRAND", :county=>"GUADELOUPE"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment