lib/fatsecret_lite.rb in fatsecret_lite-0.1.0 vs lib/fatsecret_lite.rb in fatsecret_lite-0.1.1
- old
+ new
@@ -1,8 +1,63 @@
-# frozen_string_literal: true
+# lib/fatsecret_lite.rb
+require "oauth2"
+require "rest-client"
+require "json"
-require_relative "fatsecret_lite/version"
-
module FatsecretLite
- class Error < StandardError; end
- # Your code goes here...
+ class Configuration
+ attr_accessor :client_id, :client_secret
+
+ def initialize
+ @client_id = nil
+ @client_secret = nil
+ end
+ end
+
+ @configuration = Configuration.new
+
+ class << self
+ def configure
+ yield(@configuration) if block_given?
+ end
+
+ def configuration
+ @configuration
+ end
+
+ def get_access_token
+ raise "Client ID and Client Secret must be configured" unless configuration.client_id && configuration.client_secret
+
+ client = OAuth2::Client.new(
+ configuration.client_id,
+ configuration.client_secret,
+ site: 'https://oauth.fatsecret.com',
+ token_url: 'https://oauth.fatsecret.com/connect/token'
+ )
+
+ token = client.client_credentials.get_token
+ token.token
+ end
+
+ def get_food_details(food_id)
+ access_token = get_access_token
+
+ response = RestClient.get(
+ 'https://platform.fatsecret.com/rest/server.api',
+ params: {
+ method: 'food.get.v2',
+ food_id: food_id,
+ format: 'json'
+ },
+ headers: {
+ Authorization: "Bearer #{access_token}"
+ }
+ )
+
+ JSON.parse(response.body)
+ rescue RestClient::ExceptionWithResponse => e
+ puts "Error: #{e.response}"
+ rescue StandardError => e
+ puts "An error occurred: #{e.message}"
+ end
+ end
end