How do I parse this array of hashes? - ruby-on-rails

I have the following array of hashes and I need to parse all email that are not empty:
[{:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"first_name#gmail.com", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil},
{...},
{}]
I am trying to do that this way:
- #contacts[0].each_with_index do |c, i|
- unless c[:email].blank?
%tr
%td= c[:email]
%td= check_box_tag "email_to[]", c[:email], true
But I am getting error:
An ActionView::Template::Error occurred in users#parse_data:
no implicit conversion of Symbol into Integer
How to do it right?

It's not good design to do a lot of processing in your views. It's understandable to have simple conditionals and loops, but heavy processing should occur in the controller.
Use something along these lines:
ary = [
{:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"first_name#gmail.com", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil},
{:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil},
{}
]
viewable_email = ary.reject{ |e| e.empty? || e['email'].empty? }
At this point viewable_email would contain only the hashes to be displayed. Your view would only loop over them.

#contacts.each_with_index do |c, i| ...

When you say each_with_index on a hash you will get an array like below
{:id=>"something", :first_name=>"First", :last_name=>"Name"}.each_with_index{|e,i| p e}
[:id, "something"]
[:first_name, "First"]
[:last_name, "Name"]
So, you cant say e[:id], thats why the error. As mentioned above #contacts[0] will give you the hash and not an array.

Related

Sort alphabetically hash's values in array from STRIPE API / Rails

In rails 6.1.4, I want to display the :nickname of a Product in STRIPE in DESC order. I mean S, M, L on my VIEW page and not in a random way like Stripe give us.
In their https://stripe.com/docs/api it seems we couldn't make the request on an easy way.
For this, I query #compositionsProduct = Stripe::Price.list(product: #composition.product). It returns me an Array of Hash in the data part:
=> #<Stripe::ListObject:0x3ff733e41c08> JSON: {
"object": "list",
"data": [
{"id":"price_price1","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"L","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":4500,"unit_amount_decimal":"4500"},
{"id":"price_price2","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"S","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":2500,"unit_amount_decimal":"2500"},
{"id":"price_price3","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"M","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":3500,"unit_amount_decimal":"3500"}
],
"has_more": false,
"url": "/v1/prices"
}
I want to write something like this:
Stripe::Price.list(product: #composition.product).sort_by([:nickname].reverse) but it obviously doesn't work.
I can iterate over these 3 lines, but I need to linked_to them on their Price page respectively.
<% #compositionsProduct.map do |compoPrice| %>
<%= link_to "#{compoPrice.nickname}", composition_path(compoPrice.id) %>
<% end %>
This is my farest point: #compositionsProduct.sort_by { |hash| hash[:nickname]} negative sign doesn't work, neither .reverse
What is the best way to sort_by alphabetically the values of a specific line in an array of hash?
#compositionsProduct.sort_by { |hash| hash[:nickname] }.reverse works very well.

Rails interpolate action_name

I have the following code structure:
<% types = [
{
one: 'one 1',
two: 'two 2',
three: 'three 3'
}
] %>
<% result = types[:#{action_name}]%>
<% puts result %>
The one, two and three are actions I have, which I want to interpolate in the result variable, so the result of an action would get the according object in the types array. How can I do this, what I did seems to return an error.
:#{action_name} it returns an error
Your code is wrong syntactically.
Fix is : :"#{action_name}" . And you don't need a Array of hash, only hash is enough.
<% types =
{
one: 'one 1',
two: 'two 2',
three: 'three 3'
}
%>
There is a couple of things wrong with your solution.
1) types = [{ one: "one1", ... }] is not a hash, it is an array with a hash in it. It looks like you want a hash, so it should be written as types = { one: "one1", ... }
2) You want to access an element from the hash by effectively doing types[:one]. To interpolate a variable into a symbol you need to do use the quotes, i.e. :"#{var}". So the assignment line should be result = types[:"#{action_name}"]
3) It seems you are doing this in a template, which is a strange place to variable assignment of any sort. I suggest you move all this code into a controller (for a start, at least).
If you have array of hash then you can access first array element:
types.first[:"#{action_name}"]
Or you can use loop for accessing hash.
If you need only hash then you should follow #Arup Rakshit answer.

Ruby - bad output from arrays

I have a form with a lots of these text inputs:
<%= text_field_tag 'name[seq]['+dat.id.to_s+']', dat.seq%>
After send this form I want to save them to database, I try to get the values from inputs in each loop:
unless params[:name].nil?
params[:name][:seq].each_with_index do |sq, i|
puts sq
end
end
But the output in terminal is wrong, for example if I have an input with the values
<%= text_field_tag 'name[seq][25]', 3%>
So I am going to expect the output is 3, but I will get to terminal this:
25
3
Is here something important, what I don't see?
Yes, you are missing something. Within your each_with_index block, sq will be an array and that's why you get that output.
So, what's going on here? Well, your params will contain this:
"name" => { "seq" => { "25" => "3" } }
And that means that params[:name][:seq] is this:
{ "25" => "3" }
Then you apply each_with_index to that to iterate through the Hash. If you do it like this:
params[:name][:seq].each_with_index do |(k,v), i|
puts "-#{k}-#{v}-"
end
you'll see what's going on.
If you just want the 3 then you can iterate over params[:name][:seq] as above and just look at v inside the block or, if you know what the '25' is some other way, you could just go straight there:
three = params[:name][:seq]['25']

Ruby on Rails: Interpreting a form input as an integer

I've got a form that allows the user to put together a hash.
The hashes desired end format would be something like this:
{1 => "a", 2 => "x", 3 => "m"}
I can build up something similar by having lots of inputs that have internal brackets in their names:
<%= hidden_field_tag "article[1]", :value => a %>
However, the end result is that builds a hash where all the keys are strings and not integers:
{"1" => "a", "2" => "x", "3" => "m"}
I'm currently fixing this by generating a new hash in the controller by looping over the input hash, and then assigning that to params. Is there a cleaner, DRYer way to do this?
Your params will always come in with string keys and values. The easiest way to fix this is to either write your own extension to Hash or simply inject as required:
numeric_keys = params['article'].inject({ }) do |h, (k, v)|
h[k.to_i] = v
h
end
Then you have a hash with the keys converted to integer values, as you like.
A simple extension might be:
class Hash
def remap_keys
inject({ }) do |h, (k, v)|
h[yield(k)] = v
h
end
end
end
This is much more generic and can be used along the lines of:
params['article'].remap_keys(&:to_i)
That depends a bit what you want to use it for. Maybe it is easier to just use strings as keys, and do the "conversion" when accessing the array (or not at all)?
It is also possible to build an array using something like
<%= hidden_field_tag "article[]", :value => "x" %>
this will return "article" as an array, and you can access it directly by index. However, there is no way to influence the position - the array will contain all values in order of appearance.
Lastly, you can make your own version of Hash or just modify the keys, as has been explained.

Passing hash as values in hidden_field_tag

I am trying to pass some filters in my params through a form like so:
hidden_field_tag "filters", params[:filters]
For some reason the params get changed in the next page. For example, if params[:filters] used to be...
"filters"=>{"name_like_any"=>["apple"]} [1]
...it gets changed to...
"filters"=>"{\"name_like_any\"=>[\"apple\"]}" [2]
note the extra quotations and backslashes in [2] when compared to [1].
Any ideas? I'm attempting to use this with searchlogic for some filtering, but I need it to persist when I change change objects in forms. I would prefer not to have to store it in session.
My solution was just to re-create each of param with key-value pair:
<% params[:filters].each do |key,value| %>
<%= hidden_field_tag "filters[#{key}]",value %>
<% end %>
You actually want/need to 'serialize' a hash using hidden fields.
Add this to your ApplicationHelper :
def flatten_hash(hash = params, ancestor_names = [])
flat_hash = {}
hash.each do |k, v|
names = Array.new(ancestor_names)
names << k
if v.is_a?(Hash)
flat_hash.merge!(flatten_hash(v, names))
else
key = flat_hash_key(names)
key += "[]" if v.is_a?(Array)
flat_hash[key] = v
end
end
flat_hash
end
def flat_hash_key(names)
names = Array.new(names)
name = names.shift.to_s.dup
names.each do |n|
name << "[#{n}]"
end
name
end
def hash_as_hidden_fields(hash = params)
hidden_fields = []
flatten_hash(hash).each do |name, value|
value = [value] if !value.is_a?(Array)
value.each do |v|
hidden_fields << hidden_field_tag(name, v.to_s, :id => nil)
end
end
hidden_fields.join("\n")
end
Then, in view:
<%= hash_as_hidden_fields(:filter => params[:filter]) %>
This should do the trick, even if you have a multilevel hash/array in your filters.
Solution taken http://marklunds.com/articles/one/314
I just wrote a gem to do this called HashToHiddenFields.
The core of the gem is this code:
def hash_to_hidden_fields(hash)
query_string = Rack::Utils.build_nested_query(hash)
pairs = query_string.split(Rack::Utils::DEFAULT_SEP)
tags = pairs.map do |pair|
key, value = pair.split('=', 2).map { |str| Rack::Utils.unescape(str) }
hidden_field_tag(key, value)
end
tags.join("\n").html_safe
end
Here's how I managed to pass a parameter value through my view - that is, from View A through View B and on to the controller:
In View A (index):
<%= link_to 'LinkName', {:action => "run_script", :id => object.id} %>
In View B (run_script):
<%= form_tag :action => 'index', :id => #object %>
<%= hidden_field_tag(:param_name, params[:id]) %>
In the controller:
Just reference params[:param_name] to make use of the value.
The key transition that wasn't documented anywhere I could find is where {... :id => object.id} from View A is passed on to View B as <%... :id => #object %>, which View B then passes on to the controller as (:param_name, params[:id]) through the hidden_field_tag construct.
I didn't see this documented anywhere but after perusing several posts across several sites including this post (whose syntax provided the key inspiration), the solution finally gelled. I've seen the caveats on hidden fields pertaining to security but have found no other way to do this given my current design, such as it is.
it's because when you convert in HTML with your hidden_field_tag, the backquote is add. After when you received it like a string not a Hash.
The Hash type can't exist in HTML. You have only string. So if you want pass your hash (not recommend by me), you need eval it when you received it. But can be a big security issue on your application.
As a caveat to Vlad's answer, I had to use raw:
<%= raw hash_as_hidden_fields(:filter => params[:filter]) %>
to get it to work in Rails 3.1.1. Essentially, the text being output was being escaped, eg., "<" becoming "&lt".
Assuming the hash is strings, symbols, numbers, and arrays, you can call eval to convert the params string of the hash from the hidden_fields form back into a hash in the controller. Then the backslash escape characters for the quotes added are no longer an issue:
hash = eval(params["hash_string"].to_s)
Credit to the following article for helping identify this simple solution for my case:
How do I convert a String object into a Hash object?
Keep in mind the contents of the params should be cleaned with .require and .permit.

Resources