nutritionix-mod 1.1.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: 9728df65e13f4fcb5b33222c3b2468c2bb1c5f8f
4
+ data.tar.gz: 76fdcb697b85af2caea421f65512bddf0047ae81
5
+ SHA512:
6
+ metadata.gz: 23f87b852586677f2e0575e9ad4943961664fc99db777cc9058464e927065544634f8a5cd56d1175d5610b8f1d56c97c8649be181381bef81e0234d92c843699
7
+ data.tar.gz: 9900c73387e31decd42df166d5eab6800cb3f6fcd48a131dfb0853b88bcac195a5bebac94efc440f37b57030479fce98e62d01c05af094681a1752944837ddc1
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ .idea/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in nutritionix.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Fazle Taher
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # Nutritionix
2
+
3
+ TODO: Write a gem description
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'nutritionix'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install nutritionix
18
+
19
+ ## Usage
20
+
21
+ * For NXQL Supported search:
22
+
23
+ app_id = '<YOUR_APP_ID>'
24
+ app_key = '<YOUR_APP_KEY>'
25
+ provider = Nutritionix::Api_1_1.new(app_id, app_key)
26
+ search_params = {
27
+ offset: 0,
28
+ limit: 50,
29
+ fields: ['brand_id', 'brand_name', 'item_id', 'item_name', 'nf_calories'],
30
+ query: 'potato'
31
+ }
32
+ results_json = provider.nxql_search(search_params)
33
+ puts "Results: #{results_json}"
34
+
35
+ * Note:
36
+ * There is a standalone test script **/script/test_api_1_1.rb** available
37
+ which can be readily used for testing.You only need to replace &lt;YOUR_APP_ID&gt;
38
+ and &lt;YOUR_APP_KEY&gt; with your nutritionix app credentials.
39
+
40
+ * Logs generated can be found at default location &lt;HOME_DIRECTORY&gt;/nutritionix_api_logs.txt
41
+
42
+ ## Contributing
43
+
44
+ 1. Fork it
45
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
46
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
47
+ 4. Push to the branch (`git push origin my-new-feature`)
48
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,3 @@
1
+ module Nutritionix
2
+ VERSION = "1.1.0"
3
+ end
@@ -0,0 +1,203 @@
1
+ require "rest-client"
2
+ require "cgi"
3
+ require 'logger'
4
+ require 'active_support/json'
5
+
6
+ module Nutritionix
7
+ # Reference: https://github.com/mftaher/nutritionix-api-ruby-library/blob/master/lib/nutritionix.rb
8
+ class Api_1_1
9
+ attr_accessor :app_id, :app_key, :app_url
10
+ attr_accessor :logger
11
+
12
+ #
13
+ # Create the Nutritionix API client.
14
+ #
15
+ # @param id Nutritionix application ID
16
+ # @param key Nutritionix API key
17
+ # @param url (Optional) Nutritionix API url
18
+ #
19
+ def initialize(id, key, url="https://api.nutritionix.com/v1_1", logger=APILogger.default_logger)
20
+ @app_id = id
21
+ @app_key = key
22
+ @app_url = url
23
+ @logger = logger
24
+ end
25
+
26
+ # Sends a POST request to the Nutritionix API Server
27
+ #
28
+ # @param endpoint The endpoint to send the request to.Current valid type is: search
29
+ #
30
+ # @param params a hash containing required query, filters, etc options as defined
31
+ # by https://developer.nutritionix.com/docs/v1_1 Nutritionix Querying Language
32
+ # (NXQL) convertible to a valid JSON.
33
+ #
34
+ # @return The request result or error as json string
35
+ #
36
+ def post_request(endpoint, params={})
37
+ params = sanitize_params(params)
38
+ add_creds_to_params(params)
39
+
40
+ params_json = params.to_json
41
+ logger.debug "======POST Request Params Json: #{params_json}"
42
+
43
+ url = [@app_url, endpoint].join('/')
44
+ logger.debug "POST request URL: #{url}"
45
+ begin
46
+ # Reference: http://rubydoc.info/gems/rest-client/1.6.7/RestClient.post
47
+ response = RestClient.post(url, params_json, content_type: 'application/json')
48
+ rescue Exception => e
49
+ logger.error "==================================================="
50
+ logger.debug "An exception occured while processing POST request to url: #{url}"
51
+ logger.error e.to_s
52
+ logger.error "==================================================="
53
+ response = { error: e.message}.to_json
54
+ end
55
+
56
+ response
57
+ end
58
+
59
+ # Sends a GET request to the Nutritionix API Server
60
+ #
61
+ # @param query string Query or search term / phrase
62
+ # @param endpoint The endpoint to send the request to.Current valid type is: search, item, brand
63
+ #
64
+ # @param params a hash containing required query, filters, etc options as defined
65
+ # by https://developer.nutritionix.com/docs/v1_1 Nutritionix Querying Language
66
+ # (NXQL) convertible to a valid JSON.
67
+ #
68
+ # @return The request result or error as json string
69
+ #
70
+ def get_request(query, endpoint, params={})
71
+ query = ::CGI::escape(query)
72
+ params = sanitize_params(params)
73
+ add_creds_to_params(params)
74
+
75
+ serialized_params = serialize_params(params)
76
+
77
+ url_components = [@app_url, endpoint]
78
+ if 'item' == endpoint
79
+ # Heroku using older version of Ruby prepend method on String is
80
+ # not available.Thus using String's insert method
81
+ serialized_params.insert(0, "id=#{query}&")
82
+ else
83
+ url_components << query
84
+ end
85
+
86
+ url = "#{url_components.join('/')}?#{serialized_params}"
87
+ logger.debug "GET request URL: #{url}"
88
+ header = {}
89
+ begin
90
+ response = RestClient.get url, header
91
+ rescue Exception => e
92
+ logger.error "==================================================="
93
+ logger.debug "An exception occured while processing GET request to url: #{url}"
94
+ logger.error e.to_s
95
+ logger.error "==================================================="
96
+ response = { error: e.message}.to_json
97
+ end
98
+
99
+ response
100
+ end
101
+
102
+ #
103
+ # Pass a search term into the API like taco, or cheese fries, and the
104
+ # NutritionIX API will return an array of matching foods.
105
+ #
106
+ # @param term string The phrase or terms you would like to search by
107
+ # @param range_start integer (Optional)Start of the range of results to view a section of up to 500 items in the "hits" array
108
+ # @param range_end integer (Optional)End of the range of results to view a section of up to 500 items in the "hits" array
109
+ # by default, the api will fetch the first 10 results
110
+ # @param cal_min integer (Optional)The minimum number of calories you want to be in an item returned in the results
111
+ # @param cal_max integer (Optional)The maximum number of calories you want to be in an item returned in the results
112
+ # @param fields strings (Optional)The fields from an item you would like to return in the results.
113
+ # Supports all item properties in comma delimited format.
114
+ # A null parameter will return the following item fields only: item_name, brand_name, item_id.
115
+ # NOTE-- passing "*" as a value will return all item fields.
116
+ # @param brand_id string (Optional)Filter your results by a specific brand by passing in a brand_id
117
+ #
118
+ # @return The search results as json string
119
+ #
120
+ def search(term, range_start = 0, range_end = 10, cal_min = 0, cal_max = 0, fields = NIL, brand_id = NIL)
121
+ get_request(term, 'search', {
122
+ :results => "#{range_start}:#{range_end}",
123
+ :cal_min => "#{cal_min}",
124
+ :cal_max => "#{cal_max}",
125
+ :fields => fields,
126
+ :brand_id => brand_id,
127
+ })
128
+ end
129
+
130
+ def nxql_search(search_params={})
131
+ # Default sort options
132
+ sort_options = {
133
+ sort: {
134
+ field: "_score",
135
+ order: "desc"
136
+ }
137
+ }
138
+
139
+ search_params.merge!(sort_options) unless search_params[:sort].nil?
140
+
141
+ logger.debug "Nutritionix::Api_1_1 NXQL search params: #{search_params}"
142
+
143
+ post_request('search', search_params)
144
+ end
145
+
146
+ #
147
+ # This operation returns an item object that contains data on all its nutritional content
148
+ #
149
+ # @param id string The id of the food item whose details are needed
150
+ #
151
+ # @return the item details as json string
152
+ #
153
+ def get_item(id)
154
+ get_request(id, 'item', {})
155
+ end
156
+
157
+ private
158
+
159
+ def add_creds_to_params(params)
160
+ params[:appId] = @app_id
161
+ params[:appKey] = @app_key
162
+ end
163
+
164
+ def sanitize_params(params)
165
+ params = {} unless params.is_a? Hash
166
+ params
167
+ end
168
+
169
+ def serialize_params(params)
170
+ request_params = []
171
+ params.each do |key, value|
172
+ request_params << "#{key}=#{::CGI::escape(value)}" unless value.nil?
173
+ end
174
+ request_params.join('&')
175
+ end
176
+
177
+ end
178
+
179
+ class APIException < Exception
180
+
181
+ end
182
+
183
+ # http://ruby.about.com/od/tasks/a/logger.htm
184
+ class APILogger
185
+ attr_reader :logger_instance
186
+ attr_accessor :file
187
+
188
+ # @param logger the logger instance to be used for logging
189
+ # @param file. Default outputs log to <HOME_DIR>/nutritionix_api_logs.txt
190
+ def initialize(logger=nil, file=File.join(Dir.home, 'nutritionix_api_logs.txt'))
191
+ @file = file
192
+ @logger_instance = logger || Logger.new(@file)
193
+ end
194
+
195
+ # Returns the default logger(Logger) instance distributed by Ruby in its
196
+ # standard library.
197
+ def self.default_logger
198
+ logger = APILogger.new
199
+ logger.logger_instance
200
+ end
201
+
202
+ end
203
+ end
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'nutritionix-mod/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "nutritionix-mod"
8
+ spec.version = Nutritionix::VERSION
9
+ spec.authors = ["Fazle Taher"]
10
+ spec.email = ["ftaher@gmail.com"]
11
+ spec.description = %q{Nutritionix API ruby wrapper, with API 1.1 as default}
12
+ spec.summary = %q{ruby gem for nutritionix API}
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_dependency "rest-client"
22
+ spec.add_development_dependency "bundler", "~> 1.3"
23
+ spec.add_development_dependency "rake"
24
+ spec.add_development_dependency "rspec"
25
+
26
+ end
@@ -0,0 +1,21 @@
1
+ require_relative '../lib/nutritionix/api_1_1'
2
+
3
+ def nxql_search_params
4
+ fields = %w(brand_id brand_name item_id item_name nf_serving_size_qty nf_serving_size_unit)
5
+ fields << %w(nf_calories nf_total_carbohydrate nf_sodium nf_dietary_fiber nf_protein)
6
+ default_fields = fields.flatten
7
+
8
+ {
9
+ offset: 0,
10
+ limit: 50,
11
+ fields: default_fields
12
+ }
13
+ end
14
+
15
+ app_id = '<YOUR_APP_ID>'
16
+ app_key = '<YOUR_APP_KEY>'
17
+ provider = Nutritionix::Api_1_1.new(app_id, app_key)
18
+ search_params = nxql_search_params
19
+ search_params.merge!(query: 'potato')
20
+ results_json = provider.nxql_search(search_params)
21
+ puts "Results: #{results_json}"
@@ -0,0 +1,34 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Nutritionix API' do
4
+ let(:agent){ Nutritionix::API.new(APP_ID,APP_KEY)}
5
+ subject(:search_params){{:results => "0:10",
6
+ :cal_min => nil,
7
+ :cal_max => nil,
8
+ :fields => nil,
9
+ :brand_id => nil}}
10
+ it 'should return serialized parameters from hash' do
11
+ serialized = agent.get_serialized_params(search_params)
12
+ serialized.should == "results=0%3A10&appId=#{agent.app_id}&appKey=#{agent.app_key}"
13
+ end
14
+
15
+ it 'should search for a food nutrition' do
16
+ results = JSON.parse(agent.search('tacos', 0, 5, 0, 0, '*'))
17
+ results.should_not be_nil
18
+ end
19
+
20
+ it 'should return an item object that contains data on all its nutritional content' do
21
+ results = JSON.parse(agent.get_item('eajmz6GbcLXtMluFNhEr'))
22
+ results.should_not be_nil
23
+ end
24
+
25
+ it 'should return a brand object that contains data on all its nutritional content' do
26
+ results = JSON.parse(agent.get_brand('SQksuzwib4H1h9'))
27
+ results.should_not be_nil
28
+ end
29
+
30
+ it 'should return application error without app id and key' do
31
+ #{"error_message"=>"application with id=\"\" was not found", "error_code"=>"application_not_found"}
32
+ pending
33
+ end
34
+ end
@@ -0,0 +1,24 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # Require this file using `require "spec_helper"` to ensure that it is only
4
+ # loaded once.
5
+ #
6
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
7
+ require 'rspec'
8
+ require 'json'
9
+ require_relative "../lib/nutritionix"
10
+
11
+ APP_ID=''
12
+ APP_KEY=''
13
+
14
+ RSpec.configure do |config|
15
+ config.treat_symbols_as_metadata_keys_with_true_values = true
16
+ config.run_all_when_everything_filtered = true
17
+ config.filter_run :focus
18
+
19
+ # Run specs in random order to surface order dependencies. If you find an
20
+ # order dependency and want to debug it, you can fix the order by providing
21
+ # the seed, which is printed after each run.
22
+ # --seed 1234
23
+ config.order = 'random'
24
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nutritionix-mod
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Fazle Taher
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-06-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rest-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: '1.3'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: '1.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Nutritionix API ruby wrapper, with API 1.1 as default
70
+ email:
71
+ - ftaher@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - .gitignore
77
+ - .rspec
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - lib/nutritionix-mod.rb
83
+ - lib/nutritionix-mod/version.rb
84
+ - nutritionix-mod.gemspec
85
+ - script/test_api_1_1.rb
86
+ - spec/nutritionix_spec.rb
87
+ - spec/spec_helper.rb
88
+ homepage: ''
89
+ licenses:
90
+ - MIT
91
+ metadata: {}
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - '>='
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - '>='
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubyforge_project:
108
+ rubygems_version: 2.2.1
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: ruby gem for nutritionix API
112
+ test_files:
113
+ - spec/nutritionix_spec.rb
114
+ - spec/spec_helper.rb