ruby gem that prepares data for datatables - ruby-on-rails

I'd like to use datatables in my rails application but I'd like to avoid prepraring JSON data by myself, so I'm looking for a gem that does it. Ideally I'd pass an ActiveRecored Relation and the gem generated JSON that could be consumed by datatables, for example:
class ItemsController < ApplicationController
def index
# I fetch data I need (taking into account authorization, search etc.)
#items = Item.find_relevant_items
respond_to do |format|
# gem prepares JSON for datatables
format.json { ItemDatatable.new(#items) }
# ...
end
end
end
I'm aware that there are several gems availabe. However, they don't suit me: jquery-datatables-rails is just a wrapper for the JS and the others seem to be outdated or not maintained (ajax-datatables-rails, rails_datatables, simple_datatables).
Do you know about any gem that would serve data for datatables?

Ruby's JSON module is built-in, just require 'json' at the top of a Ruby script to make it available. See "How do I parse JSON with Ruby on Rails?" for more information.
Rails also includes JSON capability too. See "Understanding Ruby and Rails: Serializing Ruby objects with JSON" for info using JSON and Rails. Rails is a fast-moving platform so that might be a bit out of date, but it should get you started. "Lightning JSON in Rails" is a good read for things to pay attention to as you generate JSON.
"JSON implementation for Ruby" is a great reference for Ruby and JSON also.

The best way I have found to using datatables in a rails app is this:
jquery-datatables-rails gem to get all the assets datatables needs
ajax-datatables-rails gem to get the the JSON datatables expects when using server side pagination and searching.
There are other gems that make it easier to generate the JSON datatables need If you don't want to go through the trouble of making a new class like in the RailsCast. You can find them here

RABL and JBuilder both spring to mind.
They are json template handlers and awesomely simple to use and both are equally powerfull enabling complete customisation of your json output.
There are railscasts on them both
http://railscasts.com/episodes/320-jbuilder
http://railscasts.com/episodes/322-rabl
and the sites
https://github.com/rails/jbuilder
https://github.com/nesquena/rabl
Both are well maintained.
Otherwise the datatables-rails gem is really the best option for you
http://railscasts.com/episodes/340-datatables?view=asciicast
UPDATE 2
It's the gem you have already looked at
As per railscast the gem is defined in the Gemfile
group :assets do
gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails'
gem 'jquery-ui-rails'
end
I strongly urge you to watch that railscast (http://railscasts.com/episodes/340-datatables?view=asciicast) as there are other configurations needed.

Related

Rails bootstrap gem monkeypatching method not working

I'm using the excellent twitter-bootstrap-rails gem. There is a helper within that gem (NavbarHelper) which is used to generate Bootstrap navbars with a Ruby helper. I want to monkey patch the gem such that the dropdown lists won't have carets.
So, I looked into the source and found the relevant method here. All I have to do is override it. I created a new file in config/initializers called navbar.rb with the following content:
NavbarHelper.module_eval do
def name_and_caret(name)
"HELLO WORLD"
end
end
Presumably, all of the dropdown titles then should be rendered as "HELLO WORLD" in my app (as referenced by the gem source). However, this is not occurring, and the gem does not appear to be monkeypatched at all.
I tried placing puts NavbarHelper.methods - Object.methods in the initializers file, and there were no results, which makes me think that Rails is not loading the gem correctly before the initializers. I have also checked and verified that the gem is not using autoload for its helpers.
Edit
What may be complicating this is the fact that my Gemfile includes the gem in the following manner:
gem 'twitter-bootstrap-rails', git: 'git://github.com/seyhunak/twitter-bootstrap-rails.git', branch: 'bootstrap3'
I'm not sure if this specific versioning means the monkeypatching doesn't work.
Edit #2
It seems there is only one version of the gem on my system, so I don't think that's the issue. Also, I have tried placing require 'twitter-bootstrap-rails at the top of the initializers file, with no results.
The problem is that you patch the method on this module but the module already got included at this point. Try to define this in your application_helper.rb
def name_and_caret(name)
super("blub #{name}")
end

How to make a Rails 4 API with Mongoid ORM, an OAuth2 Provider?

I am trying to secure a Rails 4 API by making it a OAuth2 Provider.
Added the gem Mongoid '4.0.0' (from the master branch of the Git Repo) to make it work with Rails 4.
Now I wish to use Doorkeeper gem to make the API an OAuth2 Provider.
I guess Doorkeeper doesn;t support Mongoid 4
(Source: https://github.com/applicake/doorkeeper/issues/224)
Moreover, I can't use Mongoid 3.1.2 as this wont work in Rails 4.
I prefer not to use the gem 'oauth-plugin' due to too much of Boilerplate code it injects.
Please suggest, Is there anything I can do to get it working?
Thank you in advance! :-)
Moped’s BSON has been removed of bson gem 2.0, but you may add this manually.
Create
config/initializers/bson/object_id.rb
Into file add:
module Moped
module BSON
ObjectId = ::BSON::ObjectId
class Document < Hash
class << self
def deserialize(io, document = new)
__bson_load__(io, document)
end
def serialize(document, io = "")
document.__bson_dump__(io)
end
end
end
end
end
Link to original article

What is the fastest way to render json in rails

I'm optimizing some slow transactions in our Rails application and a I see significant time spent rendering JSON views:
Rendered welcome/index.json.rabl (490.5ms)
Completed 200 OK in 1174ms (Views: 479.6ms | ActiveRecord: 27.8ms)
Assuming that the API call is returning exactly the data it needs to return, What is the fastest way to render JSON in rails?
We are using Rabl because of the ability to share code easily, but we aren't tied to it.
Currently oj seems to be the fastest renderer - beating yajl (according to the oj author's comparison).
Oj is used by default in the latest multi_json (and rails uses mutli_json by default), so swapping to oj should be as simple as adding the following to your Gemfile:
# Gemfile
gem "oj"
Then each time you call render, it will now use oj.
render :json => { ... } # uses multi_json which uses oj
Oj also provides additional specific interfaces, if you want even more performance, but sticking to multi_json makes it easier to swap out gems in the future.
Note that if you have any { ... }.to_json calls - these will not be upgraded to use oj unless you call Oj.mimic_JSON in an initializer.
Rails 3 uses multi_json, but it only uses it for json decoding, not encoding. Json encoding/rendering/generation uses ActiveSupport JSON library's to_json method, therefore is always slow (even if you uses Oj gem).
You can explicitly rendering using multi_json by doing:
render :json => MultiJson.dump(#posts)
Or you can try rails-patch-json-encode gem (by me) which will use multi_json by default. It will affect all build-in to_json methods, so make sure all the tests passes.
Rabl uses multi_json for compatibility across platforms and doesn't use the quite fast Yajl library by default. Rabl's config documentation explains the solution:
# Gemfile
gem 'yajl-ruby', :require => "yajl"
In the event that still isn't performant enough, you might want to explore a different JSON serializer like oj. You could also instrument your render and see where the bottleneck exists.
Netflix recently released a new JSON rendering library which is supposedly 25-40 times faster than the default library. Announcement. Code. You'll need to create a new Serializer to take advantage of it, but for people who are impacted, that doesn't seem to be a big hurdle.

What's the best way to use yajl-ruby with my Rails project?

Rails 2.3.6 started using the fast new json library, yajl-ruby, "if available".
In the "JSON gem Compatibility API" section of the yajl-ruby readme it outlines a method to just drop in yajl-ruby inclusion and have the rest of the app seamlessly pick it up.
So, ideally, I'd like
Rails to use it
My gems to use it
My application code to use it
What's the easiest way to achieve this? My guess:
config.gem 'yajl-ruby', :lib => 'yajl/json_gem'
As the very first gem in environment.rb. Doing this doesn't result in any errors, but I'm not sure how to know if rails is picking it up for its own use.
Thanks!
John
I'd recommend using yajl-ruby's API directly instead of the JSON gem compatibility API mainly for the reason that the JSON gem's to_json method conflict with ActiveSupport and has had long-standing issues making them work together.
If you just do config.gem 'yajl-ruby', :lib => 'yajl' instead, you'll need to use Yajl::Parser and Yajl::Encoder directly to parse/encode objects. The advantage of this is you'll be certain there won't be any conflicts with method overrides and as such, be guaranteed your JSON encoding/parsing code will work as expected.
The disadvantage is if you're using any gems that use the JSON gem, they'll continue to do so but you're own code will use yajl-ruby.
If you wanted to, you could use your config.gem line, then in an initializer require 'yajl' so you'd have both API's loaded. The yajl/json_gem include will override anything that's using the JSON gem with yajl - to ensure this overrides those methods try to make sure require 'yajl/json_gem' happens last.
If you're using Rails 3, you can add this to an initializer:
ActionController::Renderers.add :json do |json, options|
json = Yajl.dump(json) unless json.respond_to?(:to_str)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
self.content_type ||= Mime::JSON
self.response_body = json
end
To make sure render :json => ... calls use yajl-ruby as well.
Sorry if this isn't really answering your question but I wanted to at least give the suggestion of using yajl-ruby's API directly :)

Does to_json require parameters? what about within rails?

Does to_json require parameters? what about within rails?
I started getting the error "wrong number of arguments (0 for 1)" when doing myhash.to_json
Unfortunately I'm not sure when this error started happening, but I guess it relates to some versions of either rails or the json gem. I suppose my code (in a rails controller) is using the ActiveSupport::JSON version of to_json, rather than the to_josn method supported by the json gem. ActiveSupport::JSON vs JSON
In environment.rb I have
RAILS_GEM_VERSION = '2.3.2'
and also
config.gem "json", :version=> '1.1.7'
It's just a simple hash structure containing primitives which I want to convert in my controller, and it was working, but now I can't seem to run to_json without passing parameters.
Do you have your own version of to_json defined in a model that doesn't take args? If so, make it accept *args or opts = {}
If ActiveSupport in that version of rails has to_json, why use a gem? The Gem probably redefines Object#to_json to require arguments and thats why you are getting an error.
Look in the code of the json Gem and find where to_json is defined to verify this.
to_json does not require parameters, when you're using the version provided within rails (ActiveSupport::JSON) So that error message shows that it must be trying to call the to_josn method defined in the json gem.
So my actual source of confusion was around the way rails loads these libraries.
It will load the json gem and use it within a controller, even if I don't have a line saying 'require json' because rails loads gems as defined in environment.rb, so in fact I needed to remove the line
config.gem "json", :version=> '1.1.7'
...from my environment.rb . My code had been broken since I had added that. Confusingly I do need that gem, but only for scripting I'm doing outside of rails.

Resources