ruby_px 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 44941ebae6202b2580d1303054c643bd3e713971
4
+ data.tar.gz: 4d9b8e3bc4dc2ae1156366473137d68618f31b05
5
+ SHA512:
6
+ metadata.gz: 915d7fa2b750f11a241d25b2188210e4cbcceb2041a6c501fe78df65f480e21bce23bf172be39d1972d910ad05fea61277706fe543124a2e2bd9d5371a5aebcf
7
+ data.tar.gz: 37b7bdc3faa735d97cbd04cc341e8811a49f3340b69a8e25ed21cd150e7a0520ced342c5d1fc7b7f81da786f13c941fa48c43b122f4d91cb3ff070b2451c0361
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.2.3
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.3
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in ruby_px.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Fernando Blat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # RubyPx
2
+
3
+ [![Build Status](https://travis-ci.org/PopulateTools/ruby_px.svg?branch=master)](https://travis-ci.org/PopulateTools/ruby_px)
4
+
5
+ Work with PC-Axis files using Ruby.
6
+
7
+ ## Motivation
8
+
9
+ The Spanish Statistics Institute ([INE](http://www.ine.es/welcome.shtml)) favourite format to publish
10
+ the data is PC-Axis, a semi-plain-text format which is kind of difficult to work with unless you
11
+ have a PC with Windows installed in.
12
+
13
+ There is a library in R called [pxR](https://github.com/cran/pxR) from [@gilbellosta](https://twitter.com/gilbellosta), but I don't know more alternatives in other programming languages.
14
+
15
+ ## Installation
16
+
17
+ Add this line to your application's Gemfile:
18
+
19
+ ```ruby
20
+ gem 'ruby_px'
21
+ ```
22
+
23
+ And then execute:
24
+
25
+ $ bundle
26
+
27
+ Or install it yourself as:
28
+
29
+ $ gem install ruby_px
30
+
31
+ ## Usage
32
+
33
+ ```ruby
34
+ # Load a dataset
35
+ dataset = RubyPx::Dataset.new 'spec/fixtures/ine-padron-2014.px'
36
+
37
+ # Query some metadata
38
+ dataset.title
39
+ => "Población por sexo, municipios y edad (año a año)."
40
+
41
+ dataset.units
42
+ => "personas"
43
+
44
+ dataset.source
45
+ => "Instituto Nacional de Estadística"
46
+
47
+ dataset.contact
48
+ => "INE E-mail:www.ine.es/infoine. Internet: www.ine.es. Tel: +34 91 583 91 00 Fax: +34 91 583 91 58"
49
+
50
+ dataset.last_updated
51
+ => "05/10/99" # Really, INE?
52
+
53
+ dataset.creation_date
54
+ => "20141201"
55
+
56
+ # Obtain the headings and the stubs
57
+ dataset.headings
58
+ => ["edad (año a año)"]
59
+
60
+ dataset.stubs
61
+ => ["sexo", "municipios"]
62
+
63
+ # Obtain the dimensions of the dataset
64
+ dataset.dimensions
65
+ => ["sexo", "edad (año a año)", "municipios"]
66
+
67
+ # Get the list of values of a dimension
68
+ dataset.dimension('sexo')
69
+ => ["Ambos sexos", "Hombres", "Mujeres"]
70
+
71
+ # Query the data using the method #data
72
+ # You can query the data in two ways:
73
+ # 1 - providing all the dimensions, so you'll obtain a single value
74
+ dataset.data('edad (año a año)' => 'Total', 'sexo' => 'Ambos sexos', 'municipios' => '28079-Madrid')
75
+ => "3165235"
76
+
77
+ # 2 - providing all the dimensions except one, so you'll obtain an array
78
+ dataset.data('edad (año a año)' => 'Total', 'sexo' => 'Ambos sexos')
79
+ => [....] # an array with the population of all places for all ages and both sexs
80
+
81
+ ```
82
+
83
+ ## TODO
84
+
85
+ - Allow to receive an URL as an argument
86
+ - Refactor
87
+ - Test the gem with more files
88
+ - Speed-up the parsing time
89
+
90
+
91
+ ## Development
92
+
93
+ After checking out the repository, 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.
94
+
95
+ 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).
96
+
97
+ ## Contributing
98
+
99
+ Bug reports and pull requests are welcome on GitHub at https://github.com/PopulateTools/ruby_px. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
100
+
101
+ ## Thanks
102
+
103
+ Thank you [Xavier Badosa](https://twitter.com/badosa) for inspiring me with [json-stat.org](http://json-stat.org/) and the API of
104
+ the Javascript library [json-stat.com](http://json-stat.com/).
105
+
106
+ ## License
107
+
108
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
109
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pc-axis/dataset"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,196 @@
1
+ module RubyPx
2
+ class Dataset
3
+ attr_reader :headings, :stubs
4
+
5
+ METADATA_RECORDS = ['TITLE','UNITS','SOURCE','CONTACT','LAST-UPDATED','CREATION-DATE']
6
+ HEADING_RECORD = 'HEADING'
7
+ STUB_RECORD = 'STUB'
8
+
9
+ def initialize(file)
10
+ if !File.readable?(file)
11
+ raise "File #{file} not readable"
12
+ end
13
+
14
+ @metadata = {}
15
+ @headings = []
16
+ @stubs = []
17
+ @values = {}
18
+ @data = []
19
+
20
+ parse_file(file)
21
+ end
22
+
23
+ def title
24
+ @metadata['TITLE']
25
+ end
26
+
27
+ def units
28
+ @metadata['UNITS']
29
+ end
30
+
31
+ def source
32
+ @metadata['SOURCE']
33
+ end
34
+
35
+ def contact
36
+ @metadata['CONTACT']
37
+ end
38
+
39
+ def last_updated
40
+ @metadata['LAST-UPDATED']
41
+ end
42
+
43
+ def creation_date
44
+ @metadata['CREATION-DATE']
45
+ end
46
+
47
+ def dimension(name)
48
+ @values[name] || raise("Missing dimension #{name}")
49
+ end
50
+
51
+ def dimensions
52
+ @values.keys
53
+ end
54
+
55
+ def data(options)
56
+ # Validate parameters
57
+ options.each do |k,v|
58
+ raise "Invalid value #{v} for dimension #{k}" unless dimension(k).include?(v)
59
+ end
60
+
61
+ # Return a single value
62
+ # 2D array[ i*M + j]
63
+ # 3D array[ i*(N*M) + j*M + k ]
64
+ # 4D array[ i*(N*M*R) + j*M*R + k*R + l]
65
+ if options.length == dimensions.length
66
+ offset = 0
67
+
68
+ # positions are i, j, k
69
+ positions = (stubs + headings).map do |dimension_name|
70
+ self.dimension(dimension_name).index(options[dimension_name])
71
+ end
72
+
73
+ # dimension_sizes are from all dimensions except the first one
74
+ dimension_sizes = (stubs + headings)[1..-1].map do |dimension_name|
75
+ self.dimension(dimension_name).length
76
+ end
77
+
78
+ positions.each_with_index do |p, i|
79
+ d = dimension_sizes[i..-1].reduce(&:*)
80
+ offset += (d ? p*d : p)
81
+ end
82
+
83
+ return @data[offset]
84
+
85
+ # Return an array of options
86
+ elsif options.length == dimensions.length - 1
87
+ result = []
88
+
89
+ missing_dimension = (dimensions - options.keys).first
90
+ dimension(missing_dimension).each do |dimension_value|
91
+ result << data(options.merge(missing_dimension => dimension_value))
92
+ end
93
+
94
+ return result
95
+ else
96
+ raise "Not implented yet, sorry"
97
+ end
98
+ end
99
+
100
+ def inspect
101
+ "#<#{self.class.name}:#{self.object_id}>"
102
+ end
103
+
104
+ private
105
+
106
+ def parse_file(file)
107
+ File.foreach(file) do |line|
108
+ parse_line(line.chomp)
109
+ end
110
+ return true
111
+ end
112
+
113
+ def parse_line(line)
114
+ @line = line
115
+
116
+ if @current_record.nil?
117
+ key, value = line.scan(/[^\=]+/)
118
+ set_current_record(key)
119
+ else
120
+ value = line
121
+ end
122
+
123
+ return if @current_record.nil? || value.nil?
124
+
125
+ if @type == :data
126
+ value = value.split(' ')
127
+
128
+ add_value_to_bucket(bucket,value) unless value == [';']
129
+ else
130
+ # First format: "\"20141201\";"
131
+ if value =~ /\A\"([^"]+)\";\z/
132
+ value = value.match(/\A\"([^"]+)\";\z/)[1]
133
+ add_value_to_bucket(bucket, value.strip)
134
+
135
+ # Second format: "Ambos sexos","Hombres","Mujeres";
136
+ elsif value =~ /\"([^"]+)\",?/
137
+ value = value.split(/\"([^"]+)\",?;?/).delete_if{ |s| s.blank? }.each(&:strip)
138
+ add_value_to_bucket(bucket, value)
139
+ end
140
+ end
141
+
142
+ # If we see a ; at the end of the line, close out the record so we
143
+ # expect a new record.
144
+ if line[-1..-1] == ";"
145
+ @current_record = nil
146
+ end
147
+ end
148
+
149
+ def set_current_record(key)
150
+ @current_record = if METADATA_RECORDS.include?(key)
151
+ @type = :metadata
152
+ key
153
+ elsif key == HEADING_RECORD
154
+ @type = :headings
155
+ key
156
+ elsif key == STUB_RECORD
157
+ @type = :stubs
158
+ key
159
+ elsif key =~ /\AVALUES/
160
+ @type = :values
161
+ key.match(/\"([^"]+)\"/)[1]
162
+ elsif key =~ /\ADATA/
163
+ @type = :data
164
+ key
165
+ end
166
+ end
167
+
168
+ def bucket
169
+ instance_variable_get("@#{@type}")
170
+ end
171
+
172
+ def add_value_to_bucket(bucket, value)
173
+ if @type == :data
174
+ @data.concat(value)
175
+ elsif @type == :headings || @type == :stubs
176
+ bucket << value
177
+ bucket.flatten!
178
+ else
179
+ if bucket.is_a?(Hash)
180
+ if value.is_a?(Array)
181
+ value = value.map(&:strip)
182
+ elsif value.is_a?(String)
183
+ value.strip!
184
+ end
185
+ if bucket[@current_record].nil?
186
+ bucket[@current_record] = value
187
+ else
188
+ bucket[@current_record].concat([value])
189
+ bucket[@current_record].flatten!
190
+ end
191
+ end
192
+ end
193
+ end
194
+
195
+ end
196
+ end
data/lib/ruby_px.rb ADDED
@@ -0,0 +1,5 @@
1
+ require 'active_support/all'
2
+
3
+ module RubyPx
4
+ require 'ruby_px/dataset'
5
+ end
data/ruby_px.gemspec ADDED
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "ruby_px"
7
+ spec.version = '0.2.0'
8
+ spec.authors = ["Fernando Blat"]
9
+ spec.email = ["ferblape@gmail.com"]
10
+
11
+ spec.summary = %q{Read PC-Axis files using Ruby}
12
+ spec.description = %q{Read PC-Axis files using Ruby}
13
+ spec.homepage = "https://github.com/PopulateTools/ruby_px"
14
+ spec.license = "MIT"
15
+
16
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
17
+ # delete this section to allow pushing this gem to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_runtime_dependency "activesupport", "~> 4.2", ">= 4.2.5"
30
+
31
+ spec.add_development_dependency "bundler", "~> 1.10"
32
+ spec.add_development_dependency "rake", "~> 10.0"
33
+ spec.add_development_dependency "rspec", "~> 3.4"
34
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ruby_px
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Fernando Blat
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-05-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.2'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 4.2.5
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '4.2'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 4.2.5
33
+ - !ruby/object:Gem::Dependency
34
+ name: bundler
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.10'
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.10'
47
+ - !ruby/object:Gem::Dependency
48
+ name: rake
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '10.0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '10.0'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rspec
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '3.4'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '3.4'
75
+ description: Read PC-Axis files using Ruby
76
+ email:
77
+ - ferblape@gmail.com
78
+ executables: []
79
+ extensions: []
80
+ extra_rdoc_files: []
81
+ files:
82
+ - ".gitignore"
83
+ - ".rspec"
84
+ - ".ruby-version"
85
+ - ".travis.yml"
86
+ - CODE_OF_CONDUCT.md
87
+ - Gemfile
88
+ - LICENSE.txt
89
+ - README.md
90
+ - Rakefile
91
+ - bin/console
92
+ - bin/setup
93
+ - lib/ruby_px.rb
94
+ - lib/ruby_px/dataset.rb
95
+ - ruby_px.gemspec
96
+ homepage: https://github.com/PopulateTools/ruby_px
97
+ licenses:
98
+ - MIT
99
+ metadata:
100
+ allowed_push_host: https://rubygems.org
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ required_rubygems_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ requirements: []
116
+ rubyforge_project:
117
+ rubygems_version: 2.4.5.1
118
+ signing_key:
119
+ specification_version: 4
120
+ summary: Read PC-Axis files using Ruby
121
+ test_files: []
122
+ has_rdoc: