Rails Neo4j.rb Serializers? - ruby-on-rails

In Active node how we can implement JSON serializers like active modal
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Or any other way to send customized API response?
Right now I am doing it by making custom method in controller in which response is made after iterations (no. of records)
posts.map{|x| serialize_post(x) }
def serialize_post (post)
{
id: post.id,
name: post.name
}
end

The ActiveNode gem is based off of ActiveModel, so you should be able to simply call to_json on it with all of the arguments that that supports. You should also be able to define as_json and from_json methods:
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Separately, I'm also a big fan of the JSON API standard, so for that you might want to check out the jsonapi-serializers gem
Edit:
Active model serilaizer Gem also fulfill the purpose
https://github.com/rails-api/active_model_serializers

Related

undefined method `paginate' for #<PG::Result:0x007f8f096a3390 (Converting arel result)

I have the following method:
#vulnerabilities = Vulnerability.details(filter_version_param,
filter: filter,
sort: order)
.paginate(page: page_param, per_page: 10)
The internals of this method uses arel to find the relevant information to display on a page. However when I run into the .page method from the will_paginate gem, I receive the following error:
`undefined method `paginate' for #<PG::Result:0x007f8f096a3390>`
This is due of course to the fact that the object returned is not a class from ActiveRecord. My question is whether there is a way to convert the PG class into an ActiveRecord model? A previous implementation on the application from another developer creates a Struct.new() class and feeds the values into it. I was wondering though if there was an easier way to do this.
You have two options:
for Kaminary gem as an example : convert the query result into an
array and use Kaminary.paginate_array(array_of_result).page(#pagenumber).per(#elemnts per page), but this way could have problems with large data tables since you need to load the hole table for example, then slice the page!
you can build an object that has the sufficient methods needed for the paginator to do its job.
for more explanation and information about the above two points, please chick this link.

ActiveModelSerializer with Sinatra

Can I use active_model_serializers with Sinatra? If not, is there any better way for json output in Sinatra for building a web service?
Yes, you can. However, the design and architecture of AMS is strongly focuses on ActiveModel instances, therefore if you don't use an ActiveModel-based library (such as Mongoid, ActiveRecord, etc) the choice may be overkill.
Still, the approach reflects the common Presenter pattern applied to JSON serialization. You can easily create your own simple library to extract the attributes you define from an object you pass.
Sinatra also provides some JSON serialization extensions. What they do by default, is to call as_json. That's not the best approach, it is not extremely flexible, but you can combine those two elements to create your own solution, or start from scratch.
You can, includes a json.rb inside the lib folder with the following piece of code and do require this file on your application.rb .
# lib/json.rb
module Sinatra
module JSON
def json(object, options={})
serializer = ActiveModel::Serializer.serializer_for(object, options)
if serializer
serializer.new(object, options).to_json
else
object.to_json(options)
end
end
end
end
To use just do
get '/foo' do
json Foo.find(params[:id])
end
get '/bar' do
json Bar.find(params[:id]), { scope: self }
end
I used to_json to return JSON output from Sinatra API's. It turns out that there are dozens of JSON gems for Ruby, of varying efficiency.
One approach is to create list of attributes for each object that you want to render to JSON. For example, if your User has an image that you don't want to render, you could create a blacklist for the User class:
JSON_BLACKLIST = [ 'image' ]
Then, when you render the JSON, you can call:
user.attributes.reject{|a| JSON_BLACKLIST.include?( a )}.to_json

Rails4: Get an ActiveRecord::Relation from a model or an already chained relation

I'm writing a module for ActiveRecord models. In short it's a method that can call a series of where, join and order statements. The statements are not known at the time of writing so it is not possible to use scopes. So far it works well but there is one point I'd like to improve.
Here is my method:
def filter
rel = respond_to?(:filter_scope) ? filter_scope : where(1)
# Do other stuffs with `rel`
# ...
rel
end
It first call filter_scope if it is defined, or it obtain an ActiveRecord::Relation from the target model. To do so I use where(1) to force the model to return a relation object. This works well whenever I call filter directly on the model (User.filter) or on a relation (User.order(:name).filter, User.my_scope.filter.order(:age) etc...)
But using where(1) fells a bit dirty. In Rails 3 I would be using all instead but it's depreciated in Rails 4. Any idea on how to improve this?
Thanks in advance
Note: I cannot substitute where(1) by self because there is a possibility that self would be returned from filter and User.filter would be a class, therefore not usable as a query object.
In Rails 3 I would be using all instead but it's depreciated in Rails 4.
I don't think all is depreciated, it used to return an Array (rails 3) and now returns an ActiveRecord::Relation so you should be able to use it for chaining queries.
see http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all
Returns an ActiveRecord::Relation scope object.

Serialize/De-serialize objects via HTTP, Ruby (no ROR)

There is already similar question to this but I am not satisfied with answers since I am trying to do something more complex.
I have web service which provides list/single objects. Objects are Users, Categories, etc. Here is example of object:
<UserObject name="foo" description="bar" category=<Category name="cat1" description="bar"> locations=[<Location id=1>, <Location id=2>] >
In other words objects are somewhat complex and can be arrays of those objects. I am looking for a way to:
Serialize these object to JSON or Hash string
Send them over HTTP
Deserialize them to OpenStruct objects
Service that is serializing objects is not ROR.
App that is receiving and deserializing objects is ROR.
There must be some generic way to do this, I tried using to_json and JSON.parse but it only de-serializes object to one level. So for example above I would get:
<OpenStruct name="foo" description="bar" category="{\"name\"... JSON STRING}" locations="JSON STRING">
Instead of JSON STRINGs I would like to get objects inside object as it was in original.
Ruby: 1.9.3
Thanks
Take a look at the oj gem. It allows you to serialize and deserialize ruby objects to and from json. It also has the benefit of being very fast.
After looking into oj gem and contacting it's creator Peter Ohler, who was very nice and helped, I was able to get desired effect.
require 'oj'
# user instance is nested instance
json_string = Oj.dump user
# send over http
# de-serialize without domain classes (classes created by Oj gem)
user = Oj.load(json_string, { :auto_define => true })
Thanks to #josh-voigts for letting me know about the gem.

Can I access the collection an instance method was called on in ruby on rails

I'm working on implementing a search form in a ruby on rails application. The general idea is to use form_tag to submit the search fields (via params) to a search function in the model of the class I'm trying to search. The search function will then iterate through each of the params and execute a scoping function if the name of the function appears in params.
The issue is that when I call the search on a collection like so:
#calendar.reservations.search({:search_email => "test"})
I don't know how to refer to the collection of #calendar.reservations from within the search function.
Additionally I'm confused as to why #calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.
I've got the details of the search method over here: https://gist.github.com/783964
Any help would be greatly appreciated!
I don't know how to refer to the
collection of #calendar.reservations
from within the search function.
If you use self (or Reservation, it's the same object) inside the classmethod, you will access the records with the current scope, so in your case you will see only the reservations of a particular calendar.
[edit] I looked at you search function, and I think what you want is:
def self.search(search_fields)
search_fields.inject(self) do |scope, (key, value)|
scope.send(key, value)
end
end
Additionally I'm confused as to why
#calendar.reservations.search(...)
works, but Reservations.all.search
gives me an error saying you can't
call an instance method on an array.
#calendar.reservations does not return a standard array but a (lazy) AssociationCollection, where you can still apply scopes (and classmethods as your filter). On the other hand Reservation.all returns a plain array, so you cannot execute search there (or any scope, for that matter).
You don't really need a search method at all, as far as I can tell.
Simply use where:
#calendar.reservations.where(:search_email => 'test')
I would strongly encourage you to look at the MetaSearch GEM by Ernie Miller. It handles the kind of thing you're working on very elegantly and is quite easy to implement. I suspect that your view code would almost accomplish what the GEM needs already, and this would take care of all your model searching needs very nicely.
Take a look and see if it will solve your problem. Good luck!
Reservation.all.search doesn't work because it returns all the results as an array, while Reservation.where(..) returns an ActiveRecord object (AREL). Reservation.all actually fetches the results instead of just building the query further, which methods like where, limit etc do.

Resources