Skip to content

Instantly share code, notes, and snippets.

@rubypanther
Created July 21, 2012 01:33
Show Gist options
  • Save rubypanther/3154168 to your computer and use it in GitHub Desktop.
Save rubypanther/3154168 to your computer and use it in GitHub Desktop.
delegate
module DelegateDefault
def self.included base
base.send :extend, ClassMethods
end
module ClassMethods
def delegate_default args_hsh
include InstanceMethods
args_hsh.each do |attr,parent|
define_method attr do
default attr, parent
end
end
end
end
module InstanceMethods
def default attr, parent
result = read_attribute attr
if result.blank?
source = send(parent)
result = source.send(attr) unless source.nil?
end
result
end
end
end
class MyModel < ActiveRecord::Base
belongs_to :item
delegate_default :price => :item
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment