get ruby hash key value using Erubis - ruby

I have a hash:
hash = "email_address"=>"test#example.com"
I would like to get the value from this hash which is "test#example.com" using erubis. This doesn't work:
<%
pp hash.[email_address]
%>

Did you try this?
<%= pp hash["email_address"] %>
or
<%= pp hash[:email_address] %>

Related

How to change the order for two items in .each in ruby

I have a function in my .erb file and in it I have the following:
<%select id ="dropdown">
<option disabled selected value="select"> - select - </option>
<% #variable.each do |x| %>
<%= "<option value='#{x['code']}'>#{x['description']} </option>".html_safe %>
<% end %>
<%/select>
But I need to have two items (TUA and CRL) to be displayed at the top and the rest to be displayed in alpha order (which currently is) so it should be .
<%select id ="dropdown">
<option disabled selected value="select"> - select - </option>
<% #variable.each do |x| %>
<% next if x['code'] == 'TUA' or x['code'] == 'CRL' %>
<%= "<option value='#{x['code']}'>#{x['description']} </option>".html_safe %>
<% end %>
<%/select>
How can I do that ? I have hardcoded it and I don't want that.
Not sure how #variable is declared, but what if you try arranging it in the controller?
#variable = []
#variable << Variable.find_by(code: 'TUA')
#variable << Variable.find_by(code: 'CRL')
#variables = Variable.all.order('code DESC')
#variables.each do |x|
if x.code != 'TUA' && x.code!= 'CRL'
#variable << x
end
end

.each returning entire array after iterating through each element [duplicate]

This question already has an answer here:
Rails in rendering unnecessary information
(1 answer)
Closed 8 years ago.
I have a function in ruby
def words
ret =""
res = Net::HTTP.start(url.host, url.port) {|http|http.request(req)}
res.body.each_line do |line|
words = line.split("\"")
ret << words[1] << " "
end
return ret
end
say ret returns "Bill Dan Mike Sarah".
in my view I am doing
<%= #class.words.split(" ").each do |name| %>
<p><%= name %></p>
<% end %>
Instead of just displaying each name on a line, it does
Bill
Dan
Mike
Sarah
["Bill", "Dan", "Mike", "Sarah"] #this shouldn't be printed
What is causing it to display the entire array there at the end? How do I prevent this?
Remove an extra = from first line in each:
<% #class.words.split(" ").each do |name| %>
<p><%= name %></p>
<% end %>

How can I parse string(ruby hash) to JSON or Array in Rhodes?

I have a mobile application that makes a request to my Rails backend.
The backend JSON returns the information in the following manner:
def get_data
respond_to do |format|
format.json{
data = Form.select('column1, column2').where(field:'Rhodes')
render :json => data
}
end
end
In my application (Rhodes), I'm using Rho::AsyncHttp.post and send to my webview index the data:
response = Rho::AsyncHttp.post(
:url => 'http://xyx.xyx.x.yx:3000/data/get_data.json',
:headers => {"Content-Type" => "application/json; charset=utf-8", "Accept" => "application/json"}
)
WebView.navigate( url_for :action => :index , :query => { :form => response['body'] })
Now, when I inspect the variable form in my webview I get the data in the following structure:
<%= #form.inspect %>
"[{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"}]"
So, I need to show this data in a Table and I want loop this. I tried with each:
<h2>Data</h2>
<% #form.each do |x| %>
<div><%= x.tipo %></div>
<% end %>
But I get the error: undefined method each for #.
So, I tried to convert it to a JSON object:
data = Rho::JSON.parse(#form)
But, I get the following error:
JSON error code: 10; Ofset: 9
Trace:
(eval):36:in ´parse´
(eval):36:in '´
lib/rho/render.rb:175:in ´eval_compiled_file´
lib/rho/render.rb:175:in ´render´ [...]
I'm using Ruby 1.9.3 with Rhodes 3.5.1.12
UPDATE
I fix the problem with the function eval. Now I can loop the string.
But when I try to print the variable. These not show.
<% data = eval(#form) %>
<% data.each do |hash| %>
<ul>
<li><%= puts hash['campo'] %></li> #only display the bullets but no the data
<li><%= puts hash['tipo'] %></li> #only display the bullets but no the data
</ul>
<br />
<% end %>
I don't use Rhodes, but...
You can't use JSON on this string:
"[{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"},{\"campo\"=>\"nombre\",\"tipo\"=>\"textfield\"}]"
because it isn't a JSON serialized object. The => are the giveaway. JSON serializes hashes using : to delimit the key/value pairs.
Using inspect is probably confusing you because it will turn what looks like an array of hashes into a pseudo-string. I suspect it's really this:
ary = [{"campo"=>"nombre","tipo"=>"textfield"},{"campo"=>"nombre","tipo"=>"textfield"},{"campo"=>"nombre","tipo"=>"textfield"}]
because if I inspect ary I get:
# => "[{\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}, {\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}, {\"campo\"=>\"nombre\", \"tipo\"=>\"textfield\"}]"
This is how to iterate over the array of hashes:
ary.each do |hash|
puts hash['tipo']
end
# >> textfield
# >> textfield
# >> textfield

Chef erubis template: Format output based on value's classes

In my Chef cookbook (for mailman), I want use an attribute that is a hash and contains all the configuration options I want to write into a template (similar to how it's done in the chef-client cookbook).
So I want to have in my attributes:
default[:myapp][:config] = {
"I_AM_A_STRING" => "fooo",
"I_AM_AN_INT" => 123,
"I_AM_AN_ARRAY" => ["abc", "cde"]
}
As output, I want the following (mailman compatible):
I_AM_A_STRING = 'fooo'
I_AM_AN_INT = 123
I_AM_AN_ARRAY = ['abc', 'cde']
However, it does not work.
To debug the problem, I have the following code in my erubis template:
<% node[:myapp][:config].each_pair do |key, value| -%>
<% case value.class %>
<% when Chef::Node::ImmutableArray %>
# <%= key %> is type <%= value.class %>, used when Chef::Node::ImmutableArray
<%= key %> = ['<%= value.join("','") %>']
<% when Fixnum %>
# <%= key %> is type <%= value.class %>, used when Fixnum
<%= key %> = <%= value %> #fixnum
<% when String %>
# <%= key %> is type <%= value.class %>, used when String
<%= key %> = '<%= value %>' #string
<% else %>
# <%= key %> is type <%= value.class %>, used else
<%= key %> = '<%= value %>'
<% end -%>
<% end -%>
So I want to use the case .. when to distinguish between value.class. However, none of the when conditions matches. So the output is:
# I_AM_A_STRING is type String, used else
I_AM_A_STRING = 'fooo'
# I_AM_AN_INT is type Fixnum, used else
I_AM_AN_INT = '123'
# I_AM_AN_ARRAY is type Chef::Node::ImmutableArray, used else
I_AM_AN_ARRAY = '["abc", "cde"]'
When I try when Whatever.class, the first when matches for all types.
What am I doing wrong?
Looks like you mean
<% case value %>
instead of
<% case value.class %>
That's how case..when works in ruby. It's often the case you need to switch based on value (or even a range of values ), and also on type.
It let's you do things like this in ruby (and hence also in erubis/eruby):
def f(x)
case x
when String then "#{x} is a String"
when 42 then "It's #{x==42}, x is 42"
when 21..27 then "#{x} is in 21..27"
when Fixnum then "#{x} is numeric, that's all I know"
else "Can't say."
end
end
f(1) # "1 is numeric, that's all I know"
f(25) # "25 is in 21..27"
f("hello") # "hello is a String"
f(false) # "Can't say."

How do I break out of this if and each statement?

I have the following where I want to output the first six users, and if there are more than six, just return '...'.
How would I do this?
<% users.each_with_index do |x, key| %>
<% if key <= 5 %>
<%=x.name %>
<% else %>
... <% next %>
<% end %>
<% end %>
What is the last next for ? Next will just go to the next iteration. You need to use break if you want to go out of the loop.
<%
users.each_with_index do |user, key|
if key > 5
concat('...')
break
end
concat(user.name)
end
%>
You could also
<%= users.take(6).map(&:name).join %>
<%= '...' if users.size > 6 %>

Resources