What is wrong in this ruby statement?
I am trying to do something when I am connecting to my own server(local). I found request.env from the website, so I am using that a开发者_如何学编程rray to compare my IPs.
<%
if request.env['HTTP_HOST']!="127.0.0.1"
puts request.env['HTTP_HOST']
else
puts "its Local!"
end
%>
When I run above in rails3, I get nothing printed... I am new to ruby&rails3..
When you want output in the web page, use <%= %>
, not <% %>
. The output will be the return value of the expression, so you don't want puts
.
<%=
if request.env['HTTP_HOST']!="127.0.0.1"
request.env['HTTP_HOST']
else
"its Local!"
end
%>
Note that you can also use the local?
method instead of checking environment directly.
<%=
if request.local?
"its Local!"
else
request.env['HTTP_HOST']
end
%>
If you like conciseness you can do it as one line:
<%= if request.local? then "its Local!" else request.env['HTTP_POST'] end %>
For even more view conciseness, make use of a helper method:
<%= ip_or_local %>
where in the matching view helper you put:
def ip_or_local
if request.local?
"its Local!"
else
request.env['HTTP_HOST']
end
end
For this simple case, it may be overkill but in general when you start seeing lots of code in your view, it's time to think about hiding certain things in helpers.
puts
will write to the server in this case, not to the response. so you should look for your message in the log of the server.
Do you want to print to the log or to the view?
It might be clearer if you break things up into seperate erb tags.
<% if local? %>
<%= "Text for local" %>
<% else %>
<%= "Text for remote" %>
<% end -%>
You need to use <%= %> tags for lines you want printed and <% %> tags for lines that you want logic in, like conditionals.
If you're new to rails, you should check out the peepcode rails from scratch videos, they're pretty cheap and a lot of rails developers built their base on what's in them. Railscasts are also snack sized little tutorials that will easily get you through a lot of the basics.
Recommended reading:
RUBY: The ruby pickaxe The ruby way
Rails: The Rails way Head first ruby on rails
Hope I was of some help.
精彩评论