Created
July 8, 2009 11:51
-
-
Save lukeredpath/142758 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
# a slightly modified version of multi-parameter attribute support | |
# extracted from ActiveRecord::Base for use with non-ActiveRecord classes | |
module MultiParameterSupport | |
def assign_multiparameter_attributes(pairs) | |
extract_callstack_for_multiparameter_attributes(pairs).each do |name, values| | |
send("#{name}_with_multiparameter_assignment=", *values) | |
end | |
end | |
# this is just extracted directly from ActiveRecord::Base | |
def extract_callstack_for_multiparameter_attributes(pairs) | |
attributes = { } | |
for pair in pairs | |
multiparameter_name, value = pair | |
attribute_name = multiparameter_name.split("(").first | |
attributes[attribute_name] = [] unless attributes.include?(attribute_name) | |
unless value.empty? | |
attributes[attribute_name] << | |
[ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ] | |
end | |
end | |
attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } } | |
end | |
def type_cast_attribute_value(multiparameter_name, value) | |
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value | |
end | |
def find_parameter_position(multiparameter_name) | |
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first | |
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
# You still need to implement the accessors manually as there is none of ActiveRecord's reflection-fu. | |
class MyClass | |
include MultiParameterSupport | |
attr_accessor :start_date | |
def start_date_with_multiparameter_assignment=(*args) | |
self.start_date = Date.new(*args) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment