Forum: Ruby on Rails How to access the binding of the caller within a method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
94cdcdb61f509966ac0e52f8f23ae950?d=identicon&s=25 Clive Lin (clive)
on 2009-03-02 07:32
(Received via mailing list)
Probably this is a ruby trick instead of Rails'. But the context of my
question is in Rails.
There are a lot of prompt to user in our Rails app. I don't want to
hard-code those prompt every where, since they will be change by the
product team. Then I put all of them in a yml file and load the yml
file as a hash to read the prompts in controllers.
All works fine except that sometimes there needs to be some dynamic
content in the prompts. Like
<%=boy%> kissed <%=girl%>
Then I used ERB to substitute the dynamic content:

boy = "Tom"
girl = "Jenny"
raw_string = load_yml['test_prompt']
flash[:notice]=ERB.new(raw_string).result(binding)

That works, but it make each call a bit hurt. I want to be able to
just:
flash[:notice] = properties['test_prompt'], or
flash[:notice] = properties 'test_prompt'
And it is able to substitute those local variables. So I def a method
called properties to load yml and use ERB to analyze the dynamic
content. But the problem is how to get the binding of the caller?

Or is there any other "beautiful" way to make property files dynamic?
51a194adff23a68979880edb0513b74f?d=identicon&s=25 郝伯乐 (Guest)
on 2009-03-07 15:36
(Received via mailing list)
Clive,

It seems to me that you could just pass binding to the properties
method you define. For example:

require 'erb'

def properties(text_key, b)
  return ERB.new("<%= boy %> kissed <%= girl %>").result(b)
end

boy = "Tom"
girl = "Jenny"
puts properties("something", binding)


The above outputs the expected "Tom kissed Jenny" since at the time
properties is called the method binding points to the context
containing both boy and girl.  Does this answer your question?
This topic is locked and can not be replied to.