Created
September 24, 2009 20:28
-
-
Save jhchabran/193034 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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