Created
March 6, 2012 11:54
-
-
Save marcbowes/1985856 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 NameIdCache | |
def self.included(base) | |
m = Module.new | |
base.all.each do |record| | |
m.__send__(:define_method, record.name) do | |
record.record_id # using #record_id because OpenStruct is iffy about #id | |
end | |
end | |
base.extend(m) | |
end | |
end | |
# class DeliveryState < ActiveRecord::Base | |
# include NameIdCache | |
# end | |
# For demonstration | |
class DeliveryState | |
require "ostruct" | |
def self.all | |
[ # using #record_id because OpenStruct is iffy about #id | |
{ :record_id => 1, :name => "queued" }, | |
{ :record_id => 2, :name => "downloading" }, | |
].map { |r| OpenStruct.new(r) } | |
end | |
# included late because it has to be after #all, with AR this wouldn't be an issue | |
include NameIdCache | |
end | |
puts DeliveryState.all.inspect | |
puts DeliveryState.queued.inspect | |
puts DeliveryState.downloading.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment