Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/dandlezzz/pg_flash_json

json from postgres in a flash!
https://github.com/dandlezzz/pg_flash_json

Last synced: 3 months ago
JSON representation

json from postgres in a flash!

Awesome Lists containing this project

README

        

# PgFlashJson

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'pg_flash_json'
```

And then execute:

$ bundle

Or install it yourself as:

$ gem install pg_flash_json

## Usage

PGFlashJSON turns your ActiveRecord relations into json using the power of postgres' json support.
It works by using the attributes of the model to build the proper postgres json query.

```ruby
class Post < ActiveRecord::Base
# attributes :id, :title, :content
end

Post.where(id: 1).to_pg_json
# SELECT json_agg(
# json_build_object(
# 'id', t582.id,
# 'title', t582.title,
# 'content', t582.content
# ))
# as json
# FROM(SELECT "posts".* FROM "posts" WHERE "posts"."id" = 1)t582
```
This query is run and the aliases in the above example will be generated on the fly to ensure uniqueness.

To use simply call #to_pg_json on any active record association.

## Benchmarks

Since the json is generated by postgres, we can skip object instantiation, accordingly PgFlashJson is faster when used to serialize a large number of records.
Consider the following benchmarks. These ips benchmarks call the separate json methods on 100 Post models, each one has an id, title, and content. The json they produce is identical.

```
PgFlashJson#to_pg_json
179.000 i/100ms
ActiveRecord#to_json 20.000 i/100ms
-------------------------------------------------
PgFlashJson#to_pg_json
1.819k (± 3.9%) i/s - 9.129k
ActiveRecord#to_json 208.296 (± 4.3%) i/s - 1.040k

Comparison:
PgFlashJson#to_pg_json: 1819.5 i/s
ActiveRecord#to_json: 208.3 i/s - 8.73x slower

```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. Additionally,
the bin/benchmarks task will allow you to run the benchmarks locally.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/dandlezzz/pg_flash_json.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).