Git Product home page Git Product logo

pluck_to_hash's Introduction

What is that for?

Extends ActiveRecord by adding pluck_to_hash method that returns array of hashes instead of array of arrays. Useful when plucking multiple columns for rendering json or you need to access individual fields in your view for example.

Supports pluck_to_struct since version 0.3.0. pluck_to_struct returns an array of structs.

Gem Version Build Status

Installation

Add this line to your application's Gemfile:

gem 'pluck_to_hash'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pluck_to_hash

Usage

Usage is similar to ActiveRecord.pluck, for example

Post.limit(2).pluck_to_hash(:id, :title)
#
# [{:id=>213, :title=>"foo"}, {:id=>214, :title=>"bar"}]
#

Post.limit(2).pluck_to_hash(:id)
#
# [{:id=>213}, {:id=>214}]
#

Or use the shorter alias pluck_h

Post.limit(2).pluck_h(:id)
#
# [{:id=>213}, {:id=>214}]
#

Supports select alias

User.pluck_to_hash(:id, 'created_at::date as my_date', 'created_at::time as my_time')
#
# [{:id=>23, :my_date=>Fri, 11 Jul 2014, :my_time=>2000-01-01 07:54:36 UTC},
#  {:id=>2, :my_date=>Tue, 01 Jul 2014, :my_time=>2000-01-01 14:36:15 UTC}]
#

Accepts block parameter

User.pluck_to_hash(:id, :title) do |user_hash|
  ...
end

Allows specifying the type of hash. Defaults to HashWithIndifferentAccess

User.pluck_to_hash(:id, :title, hash_type: CustomHash) do |custom_hash|
  ...
end

Using pluck_to_struct

posts = Post.limit(2).pluck_to_struct(:id, :title)
#
# [#<struct id=1, title="foo">, #<struct id=2, title="bar">]
#

posts.first.id
# 1

posts.first.title
# "foo"

or use the shorter alias pluck_s

posts = Post.limit(2).pluck_s(:id, :title)
#
# [#<struct id=1, title="foo">, #<struct id=2, title="bar">]
#

Supports block parameter as well

Post.limit(2).pluck_to_struct(:id, :title) do |post_struct|
  puts post_struct.title
end

Allows specifying the type of struct. Defaults to standard Struct.

Post.limit(2).pluck_to_struct(:id, :title, struct_type: OtherStructType) do |post_struct|
  puts post_struct.title
end

Using with Sinatra or other non-rails frameworks without ActiveSupport

Use version 0.1.4 that removes ActiveSupport dependency. HashWithIndifferentAccess is not used in that case.

Why not ActiveRecord.select or ActiveRecord.as_json?

Here are results of "benchmark" tests performed on MacBook Air. Each method did 10 runs, rejected the 2 highest and 2 lowest times and average the remaining 6. Ran these tests on about 40,000 records. We notice that pluck_to_hash is almost 4x faster than select and about 8x faster than as_json. As with all the "benchmarks", you should take these results with a pinch of salt!

# Node.pluck_h(:id, :title)
# Node.select(:id, :title).to_a
# Node.select(:id, :title).as_json

                    user     system      total        real
pluck_to_hash   0.145000   0.005000   0.150000 (  0.164836)
select          0.566667   0.010000   0.576667 (  0.590911)
as_json         1.196667   0.010000   1.206667 (  1.222286)

Contributing

  1. Fork it ( https://github.com/girishso/pluck_to_hash/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Licence

MIT License

Brought to you by: Cube Root Software © 2016

pluck_to_hash's People

Contributors

akodkod avatar andrba avatar dnnx avatar giovannibonetti avatar girishso avatar jstoks avatar mohitnatoo avatar rstacruz avatar swrobel avatar tigershen23 avatar vinu91 avatar yoshitsugu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pluck_to_hash's Issues

Is it possible to pluck from multiple tables?

Say I have the following schema:

User has many Post
Post has many Comment
Comment belongs to EmailAddress

I can easily do Post.where(user_id: user_id).pluck_to_hash which will get me all the fields of the Post. But what if I want to also get the fields of the Comments and EmailAddresses as well?

1.0.1 regression/bug

If you run a pluck_to_hash using 2 aliased operations, the result becomes weird/shifted.

Prices.pluck_to_hash('coalesce(sum(high_price - low_price), 0) as difference', 'count(prices.id) as prices_count')

gives
{
"coalesce(sum(high_price - low_price), 0)"=>#BigDecimal:b066868,'0.2E2',9(18),
"amount"=>1,
"prices_count"=>nil
}

Incorret hash returned when using joins and declarative columns

pluck can be used across multiple tables and:

While not absolutely necessary, the pluck query across multiple tables would be more safely written as pluck("users.first_name, users.last_name, roles.title") to correctly scope columns to their respective table.
http://collectiveidea.com/blog/archives/2015/05/29/how-to-pluck-like-a-rails-pro/

When I run something like pluck_to_hash("users.first_name, users.last_name, roles.title")

I get results similar to:

{"users.first_name, users.last_name, roles.title"=>["john","smith", "accountant"]} 

Doesn't work nicely with serialized attributes

class Article < ActiveRecord::Base
  serialize :tags, Array
end

Article.create!(tags: [])
Article.create!(tags: ['Zygohistomorpic', 'Prepromorphism'])
Article.create!(tags: ['Comonad'])

Article.pluck(:tags) 
# => [[], ['Zygohistomorpic', 'Prepromorphism'], ['Comonad']]

Article.pluck_to_hash(:tags) 
# => [{tags: nil}, {tags: 'Zygohistomorpic'}, {tags: 'Comonad'}]

This is not what I expect, unfortunately :( Poor prepromorphism was lost somewhere.

uninitialized constant PluckToHash::ActiveSupport (NameError)

Code:
@all_scores = DailyScore.all.pluck_to_hash(:date,:average).to_json.html_safe

On 'rackup' local serve command (am using Padrino), this is what I get:

/Users/JW/.rvm/gems/ruby-2.0.0-p353/gems/pluck_to_hash-0.2.0/lib/pluck_to_hash.rb:4:in `module:PluckToHash': uninitialized constant PluckToHash::ActiveSupport (NameError)

Added to Gemfile, bundled; tried to require it.

Any idea what to do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.