What's a tight way to reference a variable that may not be defined in a partial?
I have a few local variables in my partials which may or may not be passed by the template that renders them, for instance: on_question_page
. If I'm on the page I pass it as true but elsewhere I skip it.
The problem is th开发者_如何学Cat I can't reference that variable directly because in the places it isn't defined it throws an error.
This means that I end up with a lot of code like this at the top of my partials:
on_question_page = defined?(on_question_page) ? on_question_page : false
Messy. Is there a cleaner way to access these optional variables?
You can use on_question_page ||= false
to assign false
if on_question_page
is undefined or false
or nil
, that is, something which evaluates to false
when tested with boolean operators.
you might use ||=
operator
on_question_page ||= false
How about defining the default value at a position which is always included and overriding it in your partial?
That way you do not need to check whether it is available and you could even change the default value easily if required.
I think the solution would be to use bindings and a helper:
# whatever_helper.rb
def local_set(ref, view_binding)
eval(ref.to_s, view_binding)
rescue NameError
false
end
# my_neet_view.html.erb
<h1>Question</h1>
<%= local_set("on_question_page", binding) %>
Bindings allow us to pass the evaluation context of the view in to a helper and do all the messy work in there. This moves the logic out of the view and in to a helper.
精彩评论