How to refactor wrapper using singleton to set up session? - ruby-on-rails

module Asterisk
class Client
include HTTParty
base_uri 'https://asterisk.dev/'
def initialize(session_key = nil)
#session_key = session_key
end
def get_session_key(login, password)
self.class.put('/api/auth', query: { login: login, password: password })
end
def get_contacts
self.class.get("/api/#{#session_key}/contacts")
end
def get_contact(id)
self.class.get("/api/#{#session_key}/contact/#{id}")
end
def create_contact
self.class.put("/api/#{#session_key}/create")
end
def logout
self.class.delete("/api/#{#session_key}/logout")
end
end
end
Right now it works like below
session_key = Asterisk::Client.new.get_session_key('login', 'pass')
client = Asterisk::Client.new(session_key)
client.get_contacts
I would like to get and set session key using singleton. How to do that?

module Asterisk
class Client
include HTTParty
include Singleton
base_uri 'https://asterisk.dev/'
attr_reader :last_session_update
private
def session_key
if !#session_key || session_refresh_needed?
#session_key = set_session_key
#last_session_update = Time.now
else
#session_key
end
end
def set_session_key
self.class.put('/api/auth', query: { login: login, password: password })
end
def password
#the way you get pass
end
def login
#the way you get login (ENV...)
end
def session_refresh_needed?
return true unless last_session_update
( Time.now - last_session_update) > 30.minute
end
end
end
It includes your issue with 30 minutes refresh.
Now call Asterisk::Client.instance

Related

How can I parse a json response.body to store a key's value in ruby on rails?

I am receiving a json response (response.body) from the api call I am making with my model and in my controller I would like to parse it to store its id key's value in my session[:user_id].
I've tried to implement it in the following way
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
The response.body is:
{"result":[{"id":"3","username":"Sam","password":"111"},{"id":"4","username":"Harshal","password":"1234"},{"id":"5","username":"Dev","password":"112"},{"id":"6","username":"Lam","password":"113"},{"id":"7","username":"Tim","password":"114"},{"id":"8","username":"Harry","password":"222"}]}
The parsed_body is:
{:result=>[{:id=>"3", :username=>"Sam", :password=>"111"}, {:id=>"4", :username=>"Harshal", :password=>"1234"}, {:id=>"5", :username=>"Dev", :password=>"112"}, {:id=>"6", :username=>"Lam", :password=>"113"}, {:id=>"7", :username=>"Tim", :password=>"114"}, {:id=>"8", :username=>"Harry", :password=>"222"}]}
Here is my code for users controller, user model and sessions controller:
Users Controller
class UsersController < ApplicationController
def create
#users = User.new(token: user_params).credentials
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
redirect_to '/dashboard'
end
private
def user_params
params.require(:user).permit(:id, :username, :password).to_hash
end
end
User Model
class User
def initialize(attributes={})
#token ||= attributes[:token]
end
def credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.post('/restapitrial/index.php/Users/insert/', #token.to_json, "Content-Type" => "application/json")
end
def get_credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.get('/restapitrial/index.php/Users/displayinfo/', "Content-Type" => "application/json")
puts "The req body is #{request.body}"
return request.body
end
end
Sessions Controller
class SessionsController < ApplicationController
def create
user = User.find_by(id: login_params[:id])
if user && user.authenticate(login_params[:password])
session[:user_id] = user.id
redirect_to '/dashboard'
else
flash[:login_errors] = ['invalid credentials']
redirect_to '/'
end
end
private
def login_params
params.require(:login).permit(:id, :username, :password)
end
end
If you want to get the last id in the array that is returned then use the
parsed_body[:result][-1][:id]

Best practices for Ruby on Rails service

I'm writing some mobile otp validation service and below is my service class
require 'nexmo'
class NexmoServices
def initialize api_key = nil, api_secret = nil, opts = {}
api_key = api_key || Rails.application.secrets.nexmo_api_key
api_secret = api_secret || Rails.application.secrets.nexmo_secret_key
#nexmo_client = Nexmo::Client.new(
api_key: api_key,
api_secret: api_secret,
code_length: 6
)
#brand = 'CryptoShop'
end
def send_verification_code opts
#nexmo_client.verify.request(number: opts[:number], brand: #brand)
end
def check_verification_code opts
#nexmo_client.verify.check(request_id: opts[:request_id], code: opts[:verification_code])
end
def cancel_verification_code opts
#nexmo_client.verify.cancel(opts[:request_id])
end
end
in the controller i'm calling the service methods like below
class NexmoController < ApplicationController
def send_verification_code
response = NexmoServices.new.send_verification_code params[:nexmo]
if response.status == '0'
render json: response.request_id.to_json
else
render json: response.error_text.to_json
end
end
def cancel_verification_code
response = NexmoServices.new.cancel_verification_code params[:nexmo]
if response.status == '0'
render json: response.to_json
else
render json: response.error_text.to_json
end
end
end
I have read that usually there will be call method inside service class and controller will call that. service method call will take care of the rest.
My case im instantiating service objects for all the methods if you see my controller(NexmoService.new).
is it correct??? I want to know the best practise must be followed in this scenario.
Thanks,
Ajith

How to add access token

How to add access token for this URL http://graph.facebook.com/?id=#{checked_url}&access_token=#{access_token} instead of http://graph.facebook.com/?id=#{checked_url}
module SocialShares
class Facebook < Base
def shares!
response = RestClient.get(url, params: {
fields: 'share'
})
json_response = JSON.parse(response)
if json_response['share']
json_response['share']['share_count'] || 0
else
0
end
end
private
def url
"http://graph.facebook.com/?id=#{checked_url}"
end
end
end
Add access token to
"http://graph.facebook.com/?id=#{checked_url}#{access_token}"
private
def access_token
youracesstoken
end

Check if Form input was empty

I have the following parameters
def note_params
params.require(:note).permit(
:content
)
end
Now i am trying to check of the content was empty for :content i am passing this to a service object
def add_note_to_plan
unless #note_params.content.empty?
puts "======================================================"
note = Note.new(
note_params.merge(
plan: #plan,
user: #current_user
)
)
note.save
end
puts "=================== outside ==================================="
end
Service Object
class PlanCreator
def initialize(current_user, venue_params, plan_params, note_params)
#current_user = current_user
#venue_params = venue_params
#plan_params = plan_params
#note_params = note_params
end
attr_reader :venue, :plan
def create
#venue = new_or_existing_venue
#plan = new_or_existing_plan
save_venue && save_plan && add_current_user_to_plan && add_note_to_plan
end
def errors
{
venue: venue_errors,
plan: plan_errors,
note: note_errors
}
end
private
attr_reader :current_user, :venue_params, :plan_params, :note_params
..... Removed all the unnecessary methods
def add_note_to_plan
unless #note_params.content.empty?
puts "======================================================"
note = Note.new(
note_params.merge(
plan: #plan,
user: #current_user
)
)
note.save
end
puts "=================== outside ==================================="
end
end
Error:
NoMethodError - undefined method `content' for
{"content"=>""}:ActionController::Parameters:
Change this:
unless #note_params.content.empty?
To this:
unless #note_params[:content].empty?
ActionController's params returns a hash of parameters.

convert a ruby rails model class into a class in the lib folder

I have the following model/Admin.rb class that I would like to extract and convert into a lib/UserApi class. I am not familiar into creating lib classes and being able to call them from my controllers. Any advice appreciated.
class Admin
attr_accessor :id
attr_accessor :firstname
attr_accessor :lastname
attr_accessor :usergroups
def initialize json_attrs = {}
#usergroups = []
unless json_attrs.blank?
#id = json_attrs["id"]
#fname = json_attrs["fname"]
#lname = json_attrs["lname"]
#groups = json_attrs["groups"]
#authenticated = true
end
if json_attrs.blank?
#firstname = "blank"
end
end
def is_authenticated?
#authenticated ||= false
end
def in_groups? group_names
return !(#usergroups & group_names).empty? if group_names.kind_of?(Array)
#usergroups.include?(group_names)
end
def authenticate username, password
options={:basic_auth => {:username => CONFIG[:API_CLIENT_NAME],
:password => CONFIG[:API_CLIENT_PASSWORD]}}
api_response = HTTParty.get("#{CONFIG[:API_HOST]}auth/oauth2?username=#{username}&password=#{password}", options)
raise "API at #{CONFIG[:API_HOST]} is not responding" if api_response.code == 500 || api_response.code == 404
if api_response.parsed_response.has_key? "error"
return false
else
initialize(api_response.parsed_response["user"].select {|k,v| ["id", "fname", "lname", "groups"].include?(k) })
#authenticated = true
return true
end
end
def full_name
"#{#name} #{#name}"
end
end
This is what I currently use in the auth_controller"
class Admin::AuthController < Admin::BaseController
def auth
admin_user = Admin.new
auth_result = admin_user.authenticate(params[:username], params[:password])
end
Create the UserApi class in the lib directory:
# lib/user_api.rb
class UserApi
...
Update the controller:
class Admin::AuthController < Admin::BaseController
def auth
admin_user = UserApi.new
auth_result = admin_user.authenticate(params[:username], params[:password])
end
Load the classes you put in your lib/ directory, so they are accessible in the controller: Best way to load module/class from lib folder in Rails 3?
I typically create a config/initializers/00_requires.rb file and require the lib files I need.

Resources