How to use class_eval <<-"end_eval" in Ruby? Not parsing correctly
Posted
by viatropos
on Stack Overflow
See other posts from Stack Overflow
or by viatropos
Published on 2010-03-24T02:09:11Z
Indexed on
2010/03/24
2:13 UTC
Read the original article
Hit count: 514
I would like to define dynamic methods based on some options people give when instantiating it. So in their AR model, they'd do something like this:
acts_as_something :class_name => "CustomClass"
I'm trying to implement that like so:
module MyModule
def self.included(base)
as = Config.class_name.underscore
foreign_key = "#{as}_id"
# 1 - class eval, throws these errors
# ~/test-project/helpers/form.rb:45: syntax error, unexpected $undefined
# @ ||= MyForm.new(
# ^
# ~/test-project/helpers/form.rb:46: syntax error, unexpected ','
#~/test-project/helpers/form.rb:48: syntax error, unexpected ')',
# expecting kEND from ~/test-project/helpers.rb:12:in `include'
base.class_eval <<-"end_eval", __FILE__, __LINE__
attr_accessor :#{as}
def #{as}
@#{as} ||= MyForm.new(
:id => self.#{foreign_key},
:title => self.title
)
@#{as}
end
end_eval
end
end
But it's throwing a bunch of errors I've printed in the comments. Am I using this incorrectly? What are some better ways I can define dynamic method names and dynamic names inside the method like this? I see people use this often instead of define_method
(see these classes in resource_controller and couchrest toward the bottom). What I missing here?
Thanks for the help
© Stack Overflow or respective owner