Is there a way to covert a fixture to a set of ActionController::Parameters?
For example:
# contacts.yml
dan:
first_name: Dan
last_name: Gebhardt
email: dan#example.com
notes: Writes sample code without tests :/
joe:
first_name: Joe
last_name: Blow
email: joe#example.com
notes: Lousy plumber
# contacts_test.rb
#dan = contacts(:dan)
# create params that represent Dan?
#dan_as_params = ActionController::Parameters.new(???)
Any and all help appreciated.
You could turn the object into json and back to hash containing correct param keys thus:
h= Hash[*JSON.load(#dan.to_json).map{ |k, v| [k.to_sym, v] }.flatten]
params= {contact: h}
Update:
you can also use JSON.parse
dan= Hash[*JSON.parse(#dan.to_json, symbolize_names: true).flatten]
params= {contact: dan}
Which has its own internal way of converting json keys to symbols.
Related
Trying to iterate over an array using ruby and it is miserably failing,
My Array
people = [{first_name: "Gary", job_title: "car enthusiast", salary: "14000" },
{first_name: "Claire", job_title: "developer", salary: "15000"},
{first_name: "Clem", job_title: "developer", salary: "12000"}]
How to iterate over the above hash to output only the salary value???
I tried using:
people.each do |i,j,k|
puts "#{i}"
end
The results are as below and is not what i was intending,
{:first_name=>"Gary", :job_title=>"car enthusiast", :salary=>"14000"}
{:first_name=>"Claire", :job_title=>"developer", :salary=>"15000"}
{:first_name=>"Clem", :job_title=>"developer", :salary=>"12000"}
Is there a way to iterate through this array and simply list out only the salary values and not the rest?
In newer versions of Ruby (not sure when it was introduced, probably around ruby 2.0-ish which is when I believe keyword arguments were introduced), you can do:
people.each do |salary:,**|
puts salary
end
where ** takes all the keyword arguments that you don't name and swallows them (ie, the first_name and job_title keys in the hash). If that isn't something that your ruby version allows, you'll need to just store the entire hash in the variable:
people.each do |person|
puts person[:salary]
end
Regarding the exercises in Michael Hartl's RoR Tutorial in lesson 4.3.3 (Hashes & Symbols):
"Define a hash with symbol keys corresponding to name, email, and a “password digest”, and values equal to your name, your email address, and a random string of 16 lower-case letters."
I am hoping to get some input and/or alternative & 'better' solutions to this (or at least some criticism regarding my solution).
def my_hash
a = ('a'..'z').to_a.shuffle[0..15].join
b = { name: "John", email: "johndoe#gmail.com", password: a }
return b
end
puts my_hash
(Yes I realize this is a very simple exercise and apologize if it has been asked before.)
There are many 2 improvements could be made:
Use Array#sample to get random letters (it has an advantage: the letter might in fact repeat in the password, while shuffle[0..15] will return 16 distinct letters);
Avoid redundant local variables and especially return.
Here you go:
def my_hash
{
name: "John",
email: "johndoe#gmail.com",
password: ('a'..'z').to_a.sample(16).join
}
end
puts my_hash
Bonus:
I accidentaly found the third glitch in the original code. It should probably be:
def my_hash
{
name: "Brandon",
email: "brandon.elder#gmail.com",
password: ('a'..'z').to_a.sample(16).join
}
end
:)
So, I've been banging my head against the wall for the past couple of hours trying to get this. Also, I'll change the name of the question when I know the name of the thing below.
First question, what is this called? #<Comment:0x007fda3aaeb7c8> which is returned from the database.
Secondly, I'm trying to return (render json) a comment that contains child comments.
Something like this:
[
{
id: 1,
title:'title',
body:'body'
},
{
"#< Comment:0x007fda3b3517f0>": {},
"#< Comment:0x007fda3b3517f0>": {},
}
]
How do I return the values of those comments? When I puts them in the console it shows their attributes and values, like so:
puts comments[0][1]
{#<Comment id: 17, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}, #<Comment id: 18, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}}
but if I try to modify them at all - like to_a or to_json - it just blows up (for a lack of a better term) like such:
puts comments[0][1].to_a
#<Comment:0x007fda3b1911b8>
{}
#<Comment:0x007fda3b190fd8>
{}
I'm using Postgres, and I'm using closure_tree's hash_tree to sort the comments.
Any advice would be very much appreciated, especially with the first question.
EDIT:
The def index that returns the comments:
def index
if request.headers["type"] == 'music'
comments = Comment.where("song_id = ?", request.headers["id"]).hash_tree.to_a
comments.each do |comment|
puts comment[1] #shows all attributes and values
puts comment[1].to_a #blows up
puts comment[1].to_s #works
end
end
if comments
render json: {status:200, success:true, comments:comments}
else
render json: {status:404, success:false}
end
end
That output is the default string representation of an output - the class name plus the raw pointer value of the underlying object. Some of the things you're trying to do (such as convert to json) try to convert their input to a string (via the to_s method)
It looks like you've got comments as the key in a hash, which doesn't make sense if the output is supposed to be json - keys in JSON have to be strings.
The answer to my strugle was to use .as_json.merge!(children=>[]) then push all underlying comments into the above, then push the above into the comment
Here's the repo for anyone interested:
https://github.com/jrothrock/comments/
I'm trying to build a generator in rails but I'm getting stuck at trying to access an existing model's parameters. Basically I want to do something like this:
# user is a model the has the parameters "id: integer, name: string, and email: string"
User.parameters.each do |parameter|
# do something with id, name, email
parameter.key
# do something with integer, string, string
parameter.value
end
Any ideas?
I think what you want is this
User.columns_hash.each do |key, value|
key
value.type
end
value.type will give you the type as a symbol. You can convert it to a string if you want it as a string
I think you are looking for attributes, rather than parameters.
user = User.first
user.attributes.each do |key, value|
# do something here with keys and values
puts key if key
puts value if value
end
Notice I'm grabbing an actual instance of the model as well as checking for nils (the if key/ if value part)
Got it! Need to use columns_hash like this:
Event.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
Credit to Getting types of the attributes in an ActiveRecord object
I have a hash of hashes like so:
Parameters: {"order"=>{"items_attributes"=>{"0"=>{"product_name"=>"FOOBAR"}}}}
Given that the depth and names of the keys may change, I need to be able to extract the value of 'product_name' (in this example "FOOBAR") with some sort of search or select method, but I cannot seem to figure it out.
An added complication is that Params is (I think) a HashWithIndifferentAccess
Thanks for your help.
Is this what you mean?
if params.has_key?("order") and params["order"].has_key?("items_attributes") then
o = params["order"]["items_attributes"]
o.each do |k, v|
# k is the key of this inner hash, ie "0" in your example
if v.has_key?("product_name") then
# Obviously you'll want to stuff this in an array or something, not print it
print v["product_name"]
end
end
end