Skip to content

Instantly share code, notes, and snippets.

@marcbowes
Created March 6, 2012 11:54
Show Gist options
  • Save marcbowes/1985856 to your computer and use it in GitHub Desktop.
Save marcbowes/1985856 to your computer and use it in GitHub Desktop.
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