Created
August 30, 2012 17:08
-
-
Save hoelzro/3533581 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 MooseyFate | |
def self.included(c) | |
c.define_singleton_method :has do |name, attributes = {}| | |
unless defined? @__moosey_attrs | |
@__moosey_attrs = [] | |
end | |
attributes[:name] = name.to_sym | |
ivar = ('@' + name.to_s).to_sym | |
define_method name.to_sym do | |
instance_variable_get ivar | |
end | |
define_method (name.to_s + '=').to_sym do |value| | |
instance_variable_set ivar, value | |
end | |
@__moosey_attrs.push attributes | |
end | |
c.define_singleton_method :attributes do | |
attributes = superclass.include?(MooseyFate) ? superclass.attributes.dup : [] | |
if defined? @__moosey_attrs | |
attributes.concat(@__moosey_attrs.map { |attr| attr[:name] }) | |
end | |
attributes | |
end | |
c.class_eval do | |
define_method :initialize do |params| | |
if self.class.superclass.include?(MooseyFate) | |
super(params) | |
end | |
attrs = self.class.instance_eval do | |
if defined? @__moosey_attrs | |
@__moosey_attrs | |
else | |
[] | |
end | |
end | |
attrs.each do |attr| | |
name = attr[:name] | |
if params.has_key? name | |
value = params[name] | |
if attr.has_key? :from_document then | |
value = attr[:from_document].call(value) | |
end | |
ivar = ('@' + name.to_s).to_sym | |
instance_variable_set ivar, value | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment