Created
July 21, 2012 01:33
-
-
Save rubypanther/3154168 to your computer and use it in GitHub Desktop.
delegate
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 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 |
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
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