Question

Let's say I've got the variable @var. Usually I would use <%= @var %> to write it into the view. Now I want to call a module method from within my view which internally decides to write the content of @var or not.

Inside the module I can't use <%= %>. How can I print the content of @var from within the module? The method would be called like this: <% my_method %>. Thanks

Update Thanks for the answers so far. Maybe I should say more about my initial problem to be more clear. Sorry if I wasn't clear enough.

At first I used the <%= %> tag like this:

def print_if_present(var)
  var ? var : ""
end

<%= print_if_present var %>

But then, when the var was nil, I got "" as output, which took space in the view. How can I prevent this behavior?

Was it helpful?

Solution 2

The best way to do this is to have your method return the string and use <%= ... %> as in fotanus’ answer, but in Rails if you really need to write output directly from a helper you could use the concat method:

The preferred method of outputting text in your views is to use the <%= “text” %> eRuby syntax. The regular puts and print methods do not operate as expected in an eRuby code block. If you absolutely must output text within a non-output code block (i.e., <% %>), you can use the concat method.

So you can define a helper like this:

def my_method
  if some_condition
    concat "Something or other"
  else
    concat "Something else"
  end
end

And then use it in a non-output block:

<% my_method %>

OTHER TIPS

I assume that your module is actualy the view helper. If is that so, simply return var.

def my_method
  if my_condition
    @var
  else # else clause is optional
    @other_var
  end
end

Note that the else clause is optional. If you want to write something or nothing, you can simply use the if. This is so because if the if is not executed and there is no else, it will return nil, that will be casted to an empty string in your template. Just to ilustrate,

if true
  1
end
 => 1 #return if last value

if false
  1
end
 => nil # return nil because there is no else block

Since you still want to print the return of your method on your template, you need to keep the equal sign:

<%= my_method %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top