Permalink
Browse files

use class_eval with a string when it's possible

  • Loading branch information...
1 parent 1b7b724 commit 63dca41fb62f47d257fd778371dc9cef0fb4181e @spastorino spastorino committed Mar 22, 2011
@@ -101,8 +101,14 @@ def define_attr_method(name, value=nil, &block)
if block_given?
sing.send :define_method, name, &block
else
- value = value.to_s if value
- sing.send(:define_method, name) { value }
+ if name =~ /^[a-zA-Z_]\w*[!?=]?$/
+ sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
+ def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end
+ eorb
+ else
+ value = value.to_s if value
+ sing.send(:define_method, name) { value }
+ end
end
end
@@ -66,7 +66,11 @@ def define_read_method(symbol, attr_name, column)
if cache_attribute?(attr_name)
access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
end
- generated_attribute_methods.send(:define_method, symbol) { eval(access_code) }
+ if symbol =~ /^[a-zA-Z_]\w*[!?=]?$/
+ generated_attribute_methods.module_eval("def _#{symbol}; #{access_code}; end; alias #{symbol} _#{symbol}", __FILE__, __LINE__)
+ else
+ generated_attribute_methods.send(:define_method, symbol) { eval(access_code) }
+ end
end
end
@@ -10,8 +10,12 @@ module Write
module ClassMethods
protected
def define_method_attribute=(attr_name)
- generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
- write_attribute(attr_name, new_value)
+ if attr_name =~ /^[a-zA-Z_]\w*[!?=]?$/
+ generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
+ else
+ generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
+ write_attribute(attr_name, new_value)
+ end
end
end
end

3 comments on commit 63dca41

Member

josevalim replied Mar 29, 2011

Dobry pies.

Owner

spastorino replied Mar 29, 2011

Hahahaha

Owner

spastorino replied Mar 29, 2011

now you should be a good Dobry and refactor the code :P.
This /^[a-zA-Z_]\w*[!?=]?$/ is twice ZOMG

Please sign in to comment.