How to pass an array of hashes to controller WITHOUT form? - ruby

What I have so far is an array of hashes I'm pulling from a Website via RestClient:
def self.all_galleries
JSON.parse(RestClient.get ENV["GALLERY_API"], {:accept => :json})
end
I wanted to then pass this array to my controller, and create and save a new object for every hash to my database ONLY IF it doesn't exist without using any sort of form. What's the cleanest way of doing this?

Related

Equolent add object with userid

I use the Laravel 5.2 framework.
I have a Model called template. There are user specific layout options.
Now I want get the templates easy with
$template = App\Template::where('userid', Auth::user->id);
But if I want to add these templates I have a little problem.
App\Template::create(Request::all());
Doesnt work, because the Request has no userid
What is the typical way to save a new object with the userid?
You can just merge the Request array with an array containing the user ID. Like so:
App\Template::create(array_merge(Request:all(), array('user_id' => Auth::user->id)));

How can request params be validated to ensure they include required params and don’t include unsupported params?

This is particularly in the context of a REST API built with Ruby and Sinatra.
It's easy enough to manually check to make sure that the required params are not nil. And it's easy to iterate through a flat params hash to see if it's allowed in a whitelist.
However, when the params hash also include hashes it becomes more difficult.
One way of handling this I've thought of is converting the params hash to JSON and using a library to validate it against a JSON schema.
I have come across the sinatra-param gem but I haven't had a chance to see if it can validate sub-hashes or check for unsupported params.
Edit: Another possible way, that might make more sense is passing params directly to the model (I'm using DataMapper) and using its validation and errors instead of rewriting validations.
If each of your routes are going to take the same 4 params (IE :one, :two, :three, :four), you could set up a before filter, store an array of those four params as an instance variable in the before (which is accessible to all routes) and use a sexy little method from class Enumerable called all?:
before do
#base_params = [params[:one], params[:two], params[:three], params[:four]]
unless #base_params.all?
redirect '/error_route'
end
end
Enumerable#all? will return true only if all values in your 'collection' are not false or nil. Documentation can be found here for Ruby 1.9
Additionally if you find that you have different sets of params, you can create a hash instead of just an array of #base_params where they keys are the string value of request.request_method:
before do
#base_params = {"GET" => [params[:one], params[:two], params[:three], params[:four]],
"POST" => [params[:five], params[:six], params[:seven]],
"PUT" => [params[:one], params[:five], params[:six]]}
unless #base_params[request.request_method].all?
redirect '/error_route'
end
end

How can I get Mechanize objects from Mechanize::Page's search method?

I'm trying to scrape a site where I can only rely on classes and element hierarchy to find the right nodes. But using Mechanize::Page#search returns Nokogiri::XML::Elements which I can't use to fill and submit forms etc.
I'd really like to use pure CSS selectors but matching for classes seems to be pretty straight forward with the various _with methods too. However, matching things like :not(.class) is pretty verbose compared to simply using CSS selectors while I have no idea how to match for element hierarchy.
Is there a way to convert Nokogiri elements back to Mechanize objects or even better get them straight from the search method?
Like stated in this answer you can simply construct a new Mechanize::Form object using your Nokogiri::XML::Element retrieved via Mechanize::Page#search or Mechanize::Page#at:
a = Mechanize.new
page = a.get 'https://stackoverflow.com/'
# Get the search form via ID as a Nokogiri::XML::Element
form = page.at '#search'
# Convert it back to a Mechanize::Form object
form = Mechanize::Form.new form, a, page
# Use it!
form.q = 'Foobar'
result = form.submit
Note: You have to provide the Mechanize object and the Mechanize::Page object to the constructor to be able to submit the form. Otherwise it would just be a Mechanize::Form object without context.
There seems to be no central utility function to convert Nokogiri::XML::Elements to Mechanize elements but rather the conversions are implemented where they are needed. Consequently, writing a method that searches the document by CSS or XPath and returns Mechanize elements if applicable would require a pretty big switch-case on the node type. Not exactly what I imagined.

Redis-rb pushing hash into list

Using redis-rb, how can I push a hash into a list? Do I have to JSON encode it or is this natively supported? If so, how can I do it? I only see hset method with a key and key/value pairs.
Thanks
Storing any object (not just hash) as a JSON encoded string is one way to do it.
If your use case allows it you can also store hash IDs within the list and use SORT GET to retrieve additional values.
Example:
r.hmset('person:1', 'name','adam','age','33')
r.hmset('person:2', 'name','eva','age','28')
r.lpush('occupants', 'person:1')
r.lpush('occupants', 'person:2')
r.sort('occupants', :get => ['*->name'])
To get list names from hashes which IDs are stored within occupants list. You can retrieve multiple fields, but you will get only array back.
For more information check SORT command
A Redis list is analogous to a Ruby Array. It has no keys.
As discussed in the redis-rb documentation, if you want to store a Ruby object in a Redis value you'll need to serialize it first using e.g. JSON:
Storing objects
Redis only stores strings as values. If you want to store an object inside a key, you can use a serialization/deseralization mechanism like JSON:
>> redis.set "foo", [1, 2, 3].to_json
=> OK
>> JSON.parse(redis.get("foo"))
=> [1, 2, 3]
Your other option would be to store it as a Redis hash, as you mentioned, using e.g. HMSET, but if your only goal is to store and retrieve the object (rather than perform Redis operations on it), that's superfluous.

How can I serialize form state in Javascript/jQuery between AJAX requests?

I know how to serialize a form:
$("#attributeform").serialize()
but I want to store this in some kind of variable, like a hash, so that I can retrieve these values and resubmit them in order to transition between states.
I think you are looking for serializeArray instead. It produces an array where you can save and edit.
Actually I was able to use a simple hashtable for this. I didn't want to mess with serializeArray because I was actually looking not to hash the form values, but to hash the serialized form to ANOTHER value. Sorry if I wasn't clear.

Resources