quick question: i'm using the linkedin gem to pull user data, but my app breaks if a particular data field is blank on the user's linkedin profile. is there an optimal way to scan each profile for blankness in all data fields and pull only those that are present to prevent breaking?
here is my auth_controller...i know it is not DRY and in need of refactoring. Thanks!
require 'linkedin'
class AuthController < ApplicationController
def index
client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'])
request_token = client.request_token(:oauth_callback =>
"http://#{request.host_with_port}/callback")
session[:rtoken] = request_token.token
session[:rsecret] = request_token.secret
redirect_to client.request_token.authorize_url
end
def callback
client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'])
if session[:atoken].nil?
pin = params[:oauth_verifier]
atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
session[:atoken] = atoken
session[:asecret] = asecret
else
client.authorize_from_access(session[:atoken], session[:asecret])
end
current_user = client.profile(:fields => %w(positions educations))
#user = current_user
educations = current_user.educations.all
positions = current_user.positions.all
companies = current_user.positions.all.map{ |t| t.company }
#current_company = companies[0]['name']
#past_company_one = companies[1]['name']
#past_company_two = companies[2]['name']
#past_company_three = companies[3]['name']
#current_industry = companies[0]['industry']
#past_industry_one = companies[1]['industry']
#past_industry_two = companies[2]['industry']
#past_industry_three = companies[3]['industry']
#first_name = client.profile(:fields => ["first_name"]).first_name
#last_name = client.profile(:fields => ["last_name"]).last_name
#headline = client.profile(:fields => ["headline"]).headline
#picture = client.profile(:fields => ["picture-url"]).picture_url
#school_one_name = educations[0]['school-name']
#school_one_degree = educations[0]['degree']
#school_one_field = educations[0]['field-of-study']
#school_one_start = educations[0]['start-date']['year'].to_s
#school_one_end = educations[0]['end-date']['year'].to_s
#school_two_name = educations[1]['school-name']
#school_two_degree = educations[1]['degree']
#school_two_field = educations[1]['field-of-study']
#school_two_start = educations[1]['start-date']['year'].to_s
#school_two_end = educations[1]['end-date']['year'].to_s
#current_title = positions[0]['title']
#past_title_one = positions[1]['title']
#past_title_two = positions[2]['title']
#past_title_three = positions[3]['title']
#current_start_date = Date::MONTHNAMES[positions[0]['start-date']['month']] + " " + positions[0]['start-date']['year'].to_s
#past_start_date_one = Date::MONTHNAMES[positions[1]['start-date']['month']] + " " + positions[1]['start-date']['year'].to_s
#past_end_date_one = Date::MONTHNAMES[positions[1]['end-date']['month']] + " " + positions[1]['end-date']['year'].to_s
#past_start_date_two = Date::MONTHNAMES[positions[2]['start-date']['month']] + " " + positions[2]['start-date']['year'].to_s
#past_end_date_two = Date::MONTHNAMES[positions[2]['end-date']['month']] + " " + positions[2]['end-date']['year'].to_s
#past_start_date_three = Date::MONTHNAMES[positions[3]['start-date']['month']] + " " + positions[3]['start-date']['year'].to_s
#past_end_date_three = Date::MONTHNAMES[positions[3]['end-date']['month']] + " " + positions[3]['end-date']['year'].to_s
end
end
considering your current code may break upon any unexpected values in the response and assuming it's happening in your above callback method, you may consider just applying quick'n'dirty exception handling to your code.
for example, by simply enclosing the potentially offending code in a begin / end block and using a rescueclause to handle any exceptions:
def callback
client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'])
if session[:atoken].nil?
# ...code
else
#...code
end
# start handling exceptions here
begin
# ...potentially offending code here
current_user = client.profile(:fields => %w(positions educations))
# ...more code
#past_end_date_three = Date::MONTHNAMES[positions[3]['end-date']['month']] + " " + positions[3]['end-date']['year'].to_s
rescue
# oops, something happened:
# ...your code to handle the exception here
end
end
Related
I am trying to make an audio player program in ruby for a Uni assignment, and while trying to call the audio files into ruby, i keep running into the same error message, seen below
C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/gosu-1.4.3/lib/gosu/compat.rb:116:in `initialize': Could not parse audio file songs/Beautiful.mp3: Couldn't open songs/Beautiful.mp3 (RuntimeError)
from C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/gosu-1.4.3/lib/gosu/compat.rb:116:in `initialize'
from test.rb:141:in `new'
from test.rb:141:in `playTrack'
from test.rb:65:in `initialize'
from test.rb:185:in `new'
from test.rb:185:in `<main>'
Ive attached both the code itself and the contents on input.txt for more context, ive ommited the areas unrelated to the error to get the post size down
require 'rubygems'
require 'gosu'
class ArtWork
attr_accessor :bmp
def initialize(file)
#bmp = Gosu::Image.new(file)
end
end
class Album
attr_accessor :title, :artist, :artwork, :tracks
def initialize (title, artist, artwork, tracks)
#title = title
#artist = artist
#artwork = artwork
#tracks = tracks
end
end
class Track
attr_accessor :name, :location, :dim
def initialize(name, location, dim)
#name = name
#location = location
#dim = dim
end
end
class Dimension
attr_accessor :leftX, :topY, :rightX, :bottomY
def initialize(leftX, topY, rightX, bottomY)
#leftX = leftX
#topY = topY
#rightX = rightX
#bottomY = bottomY
end
end
class MusicPlayerMain < Gosu::Window
def initialize
super SCREEN_W, SCREEN_H
self.caption = "Music Player"
#track_font = Gosu::Font.new(25)
#album = read_album()
#track_playing = 0
playTrack(#track_playing, #album)
end
def read_track(a_file, idx)
track_name = a_file.gets.chomp
track_location = a_file.gets.chomp
leftX = X_LOCATION
topY = 100 * idx + 50
rightX = leftX + #track_font.text_width(track_name)
bottomY = topY + #track_font.height()
dim = Dimension.new(leftX, topY, rightX, bottomY)
track = Track.new(track_name, track_location, dim)
return track
end
def read_tracks(a_file)
count = a_file.gets.chomp.to_i
tracks = []
i = 0
while i < count
track = read_track(a_file, i)
tracks << track
i += 1
end
return tracks
end
def read_album()
a_file = File.new("input.txt", "r")
title = a_file.gets.chomp
artist = a_file.gets.chomp
artwork = ArtWork.new(a_file.gets.chomp)
tracks = read_tracks(a_file)
album = Album.new(title, artist, artwork.bmp, tracks)
a_file.close()
return album
end
def draw_albums(albums)
#album.artwork.draw(50, 50 , z = ZOrder::PLAYER, 0.3, 0.3)
#album.tracks.each do |track|
display_track(track)
end
end
def draw_current_playing(idx)
draw_rect(#album.tracks[idx].dim.leftX - 10, #album.tracks[idx].dim.topY, 5, #track_font.height(), Gosu::Color::RED, z = ZOrder::PLAYER)
end
def area_clicked(leftX, topY, rightX, bottomY)
if mouse_x > leftX && mouse_x < rightX && mouse_y > topY && mouse_y < bottomY
return true
end
return false
end
def display_track(track)
#track_font.draw(track.name, X_LOCATION, track.dim.topY, ZOrder::PLAYER, 1.0, 1.0, Gosu::Color::BLACK)
end
def playTrack(track, album)
#song = Gosu::Song.new(album.tracks[track].location)
#song.play(false)
end
def draw_background()
draw_quad(0,0, TOP_COLOR, 0, SCREEN_H, TOP_COLOR, SCREEN_W, 0, BOTTOM_COLOR, SCREEN_W, SCREEN_H, BOTTOM_COLOR, z = ZOrder::BACKGROUND)
end
def update
if not #song.playing?
#track_playing = (#track_playing + 1) % #album.tracks.length()
playTrack(#track_playing, #album)
end
end
def draw
draw_background()
draw_albums(#album)
draw_current_playing(#track_playing)
end
def needs_cursor?; true; end
def button_down(id)
case id
when Gosu::MsLeft
# --- Check which track was clicked on ---
for i in 0..#album.tracks.length() - 1
if area_clicked(#album.tracks[i].dim.leftX, #album.tracks[i].dim.topY, #album.tracks[i].dim.rightX, #album.tracks[i].dim.bottomY)
playTrack(i, #album)
#track_playing = i
break
end
end
end
end
end
MusicPlayerMain.new.show if __FILE__ == $0
Windwaker
Love Language
images/Love_Language.jpg
11
Beautiful
songs/Beautiful.mp3
Lucy
songs/Lucy.mp3
Nighthawk
songs/Nighthawk.mp3
Dopamine Freestyle
songs/Dopamine Freestyle.mp3
Me + You
songs/Me + You, But Mostly Me.mp3
Glow
songs/Glow.mp3
Trenches
songs/Trenches.mp3
Superstitious Fantasy
songs/Superstitious Fantasy.mp3
Love Language
songs/Love Language.mp3
Hide & Seek
songs/Hide & Seek.mp3
The Rain
songs/The Rain.mp3
I am having trouble finding a way to log out from facebook. We are logging in using window.location = '/auth/facebook' which redirects the user to a facebook login page, and calls a callback route /auth/facebook/callback(declared in developers.facebook.com) to a method in my session_controller/create.
The session_controller/create method looks like this
def create
#get auth hash from omniauth
auth = auth_hash
#data = {}
#session_data = {}
#data['id'] = auth['uid']
#data['access_token'] = auth['credentials']['token']
#time must be in iso format, see parse rest api for details under linking
#expiry = Time.at(auth['credentials']['expires_at']).iso8601
#data['expiration_date'] = #expiry
#create new linking user object
user = Parse::User::Facebook.new(#data)
# add other user information to body of PARSE::USER::FACEBOOK instance
user.body['email'] = auth['info']['email']
user.body['auth'] = true
user.body['fullname'] = auth['info']['name']
user.body['ip'] = request.remote_ip
user.body['image'] = auth['info']['image'] if auth['info']['image']
user.body['admin'] = false
user.body['facebookId'] = auth['uid']
user.body['facebookToken'] = auth['credentials']['token']
user.body['has_seen_web_tutorial'] = false
#current_user = user.save
#save necessary session information
session['name'] = #current_user['fullname']
session['points'] = #current_user['points']
session['objectId'] = #current_user['objectId']
session['sessionToken'] = #current_user['sessionToken']
session['image'] = #current_user['image']
session['location'] = #current_user['location']
#session_data['name'] = session['name']
#session_data['fullname'] = #current_user['fullname']
#session_data['points'] = session['points']
#session_data['objectId'] = session['objectId']
#session_data['image'] = session['image']
if auth['info']['image']
File.open('temp_face.png', 'wb') do |file|
file << open(auth['info']['image'], :allow_redirections => :safe).read
end
photo = Parse::File.new({
:body => IO.read("temp_face.png"),
:local_filename => "temp_face.png",
:content_type => "image/png"
})
photo.save
#user.body['image'] = photo
end
image = Parse::Object.new("ImageUploads")
image['fileKey'] = photo
image['owner'] = Parse::Pointer.new({"className" => "_User", "objectId" => session['objectId']})
image['type'] = 'profile'
#image['location']
saved_image = image.save
redirect_to listing_index_path
end
I am having trouble trying to log out. Very new to rails. Any help please?
Thank you
I don't know if it's obvious or that's what I do:
method get_counter in controller
def get_counter
id = params[:id]
login = id.split('#',2).first
cust_split = id.split('#',2).last
cust = cust_split.split('.',2).first
if login
id_address = ('ovm:b:'+cust+'/'+login)
else
id_address = ('ovm:b:'+cust)
end
raw_counter = (REDIS.hget(id_address, 'c'))
raw_counter_reset = (REDIS.hget(id_address, 'overquota_reset_c'))
raw_counter_reset_date = (REDIS.hget(id_address, 'overquota_reset_at'))
if raw_counter == nil
respond_to do |format|
flash[:alert] = 'Error : wrong syntax or not present in the database'
format.html { redirect_to action: 'index' }
end
else
raw_counter_int = raw_counter.to_i
bitwise_and_max = raw_counter_int & $mask_max
decal_max = bitwise_and_max >> 53
counter_max = 1024*(decal_max+1)
#counter_max = counter_max
counter_msg = raw_counter_int & $mask_msg
#counter_msg = counter_msg
if raw_counter_reset == '1'
#counter_reset = 'oui'
else
#counter_reset = 'non'
end
#counter_reset_date = Time.at(raw_counter_reset_date.to_i)
end
end
Now I try to separate this part :
id = params[:id]
login = id.split('#',2).first
cust_split = id.split('#',2).last
cust = cust_split.split('.',2).first
if login
id_address = ('ovm:b:'+cust+'/'+login)
else
id_address = ('ovm:b:'+cust)
end
raw_counter = (REDIS.hget(id_address, 'c'))
raw_counter_reset = (REDIS.hget(id_address, 'overquota_reset_c'))
raw_counter_reset_date = (REDIS.hget(id_address, 'overquota_reset_at'))
raw_counter_int = raw_counter.to_i
bitwise_and_max = raw_counter_int & $mask_max
decal_max = bitwise_and_max >> 53
counter_max = 1024*(decal_max+1)
#counter_max = counter_max
counter_msg = raw_counter_int & $mask_msg
#counter_msg = counter_msg
if raw_counter_reset == '1'
#counter_reset = 'oui'
else
#counter_reset = 'non'
end
#counter_reset_date = Time.at(raw_counter_reset_date.to_i)
Who stay in method get_counter. And this part :
if raw_counter == nil
respond_to do |format|
flash[:alert] = 'Error : wrong syntax or not present in the database'
format.html { redirect_to action: 'index' }
end
else
get_counter
end
That goes into the method show of controller.
Infact I try to separate the redirection in the show method because get_counter can also be used to edit the method.
I'm wondering how to limit the number of followers returned via the twitter api, or if there's a better way of returning the twitter followers of a user.
We've been challenged to create a twitter manager, and I've done most of the stuff, but I keep getting a request error when someone has a large amount of followers, as we're supposed to get the users from the twitter api and store them in a database, and the page usually times out or gives a twitter get error too many requests and locks me out for an hour. It's very hard to develop when this keeps happening, I was just wondering if there's a better way to do it?
Here is my code for the dashboard which is where the user details are returned and saved, and also where the followers are returned and save:
class DashboardController < ApplicationController
helper_method :logged_in?
def new
#just_updated = ""
Twitter.configure do |config|
# Test Account
config.consumer_key = "none-of-your-business"
config.consumer_secret = "none-of-your-business"
config.oauth_token = "none-of-your-business"
config.oauth_token_secret = "none-of-your-business"
end
#user = User.find(session[:user_id])
if #user.twitter_username.present? && #user.twitter_details_present == false
#twitter_user = Twitter.user(#user.twitter_username)
#user.no_of_followers = #twitter_user[:followers_count]
#user.profile_picture_url = #twitter_user[:profile_image_url]
#user.following = #twitter_user[:friends_count]
#user.twitter_nationality = #twitter_user[:location]
#user.no_of_tweets = #twitter_user[:statuses_count]
#user.twitter_details_present = true
#user.updated_at = Time.now
if #user.save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save1"
end
end
if (Time.now - #user.updated_at) < 10.minute && (#user.updated_at - #user.created_at) > 1.hour
Follower.where("owner = #{#user.id}").destroy_all
end
if #user.twitter_username.present?
if (#followers = Follower.where("owner = #{#user.id}")).count > 0
i = Follower.first.id
#followers.each do |follower|
if (Time.now - Follower.where("owner = #{#user.id}").first.updated_at) > 1.hour
if (follower_to_save = Follower.where(follower_id: follower[:id])).present?
follower_to_save[0].follower_username = follower[:screen_name].to_s
follower_to_save[0].owner = #user.id
follower_to_save[0].follower_nationality = follower[:location]
follower_to_save[0].no_of_followers = follower[:followers_count]
follower_to_save[0].following= follower[:friends_count]
follower_to_save[0].no_of_tweets = follower[:statuses_count]
follower_to_save[0].profile_picture_url = follower[:profile_image_url]
follower_to_save[0].updated_at = Time.now
if follower_to_save[0].save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save1"
break;
end
else
follower_to_save = Follower.new
follower_to_save.follower_id = follower[:id]
follower_to_save.owner = #user.id
follower_to_save.follower_username = follower[:screen_name]
follower_to_save.follower_nationality = follower[:location]
follower_to_save.no_of_followers = follower[:followers_count]
follower_to_save.following= follower[:friends_count]
follower_to_save.no_of_tweets = follower[:statuses_count]
follower_to_save.profile_picture_url = follower[:profile_image_url]
follower_to_save.updated_at = Time.now
if follower_to_save.save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save2"
break;
end
end
else
next
end
i=i+1
#sleep(1)
end
else
#followers = Twitter.followers(#user.twitter_username)
#followers.each do |follower|
follower_to_save = Follower.new
follower_to_save.follower_id = follower[:id]
follower_to_save.owner = #user.id
follower_to_save.follower_username = follower[:screen_name]
follower_to_save.follower_nationality = follower[:location]
follower_to_save.no_of_followers = follower[:followers_count]
follower_to_save.following= follower[:friends_count]
follower_to_save.no_of_tweets = follower[:statuses_count]
follower_to_save.profile_picture_url = follower[:profile_image_url]
follower_to_save.updated_at = Time.now
if follower_to_save.save
#just_updated = "We have just compiled your followers"
else
#just_updated = "There was a problem with your save3"
break;
end
#sleep(1)
end
end
else
#no_twitter_username = "Please go into settings and add your twitter username to start."
end
#followers = Follower.all.where("owner = #{#user.id}")
#follower_count = #followers.count
end
def logged_in?
if session[:user_id].present?
true
else
false
end
end
end
The code is pretty inefficient right now, but I'm just trying to get it working.
i ve this method. I m not at all able to understand the error which is
Couldn't find Company without an ID
in ActiveRecord::RecordNotFound in CustomersController#bulk_create
This method is written to create customers for a company in bulk by taking their name and numbers in format name:number.
The method is as follows:
def bulk_create
res = ""
comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first
comp = Company.find(comp_id)
s = SentSmsMessage.new
s.set_defaults
s.data = tmpl("command_signup_ok", customer, comp) unless params[:customer][:email].length > 0
s.data = params[:customer][:email] if params[:customer][:email].length > 0
s.company = comp if !comp.nil?
s.save
unless comp_id.blank?
params[:customer][:name].lines.each do |line|
(name, phone) = line.split(/\t/) unless line.include?(":")
(name, phone) = line.split(":") if line.include?(":")
phone = phone.gsub("\"", "")
phone = phone.strip if phone.strip.to_i > 0
name = name.gsub("\"", "")
name = name.gsub("+", "")
phone = "47#{phone}" if params[:customer][:active].to_i == 1
customer = Customer.first(:conditions => ["phone_number = ?", phone])
if customer.nil?
customer = Customer.new
customer.name = name
# customer.email
# customer.login
# customer.password
customer.accepted_agreement = DateTime.now
customer.phone_number = phone
customer.active = true
customer.accepted_agreement = DateTime.now
customer.max_msg_week = params[:customer][:max_msg_week]
customer.max_msg_day = params[:customer][:max_msg_day]
customer.selected_companies = params[:customer][:selected_companies].delete_if{|a| a.blank?}
res += "#{name} - #{phone}: Create OK<br />" if customer.save
res += "#{name} - #{phone}: Create failed<br />" unless customer.save
else
params[:customer][:selected_companies].each do |cid|
new_company = Company.find(cid) unless cid.blank?
if !new_company.nil?
if !customer.companies.include?(new_company)
customer.companies << new_company
if customer.save
res += "#{name} - #{phone}: Customer exists and the customer was added to the firm #{new_company.name}<br />"
else
res += "#{name} - #{phone}: Customer exist, but something went wrong during storage. Check if the client is in the firm.<br />"
end
else
res += "#{name} - #{phone}: Customer exists and is already on firm #{new_company.name}<br />"
end
end
end
end
s.sms_recipients.create(:phone_number => customer.phone_number)
end
s.save
s.send_as_sms
#result = res
respond_to do |format|
format.html { render "bulk_create"}
end
else
#result = "You have not selected any firm to add these users. Press the back button and try again."
respond_to do |format|
format.html { render "bulk_create"}
end
end
end
I want to update one situation here. That when i submit the form blank then it gives this error. Also if i filled the form with the values then its show the situation which the method is returning in case of fail.
res += "#{name} - #{phone}: Create failed <br />"
The tmpl method
private
def tmpl(setting_name, customer, company = nil)
text = ""
if customer.companies.count > 0
sn = "#{setting_name}_#{#customer.companies.first.company_category.suffix}".downcase rescue setting_name
text = Setting.value_by(sn) rescue ""
end
textlenth = text.length rescue 0
if textlenth < 3
text = Setting.value_by(setting_name) rescue Setting.value_by("command_error")
end
return fill_template(text, customer, company)
end
From the model customer.rb
def selected_companies=(cmps)
cmps.delete("")
# Check the old ones. Make a note if they are not in the list. If the existing ones are not in the new list, just remove them
self.companies.each do |c|
self.offer_subscriptions.find(:first, ["customer_id = ?", c]).destroy unless cmps.include? c.id.to_s
cmps.delete c.id.to_s if cmps.include? c.id.to_s
end
# Then create the new ones
cmps.each do |c2|
cmp = Company.find(:first, ["id = ?", c2])
if cmp && !c2.blank?
offerSubs = offer_subscriptions.new
offerSubs.company_id = c2
offerSubs.save
end
end
end
def selected_companies
return self.companies.collect{|c| c.id}
end
The association of customer is as follows:
has_many :offer_subscriptions
has_many :companies, :through => :offer_subscriptions
This code is written by the some one else. I m trying to understand this method but so far not being able to understand this code.
Please help.
Thanks in advance.
You are getting 'Couldn't find Company without an ID' error because your Company table doesn't contain record with id = comp_id
Change comp = Company.find(comp_id) to comp = Company.find_by_id(comp_id).
This will return nil instead of an error.
Add comp is not nil condition is already handled in your code.
Your comp_id line is returning nil.
comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first
Post the params that get passed to this function and we could hopefully find out why. In the meantime you could enclose the block in a begin - rescue block to catch these errors:
begin
<all your code>
rescue ActiveRecord::RecordNotFound
return 'Unable to find a matching record'
end
try this:
comp = ""
comp = Company.find(comp_id) unless comp_id.nil?
instead of comp = Company.find(comp_id)
further nil checking present in your code.
Reason being
params[:customer][:selected_companies].delete_if{|a| a.blank?} = []
so [].first = nil
therefor, params[:customer][:selected_companies].delete_if{|a| a.blank?}.first = nil
and comp_id is nil
So check the log file and check what is coming in the parameter "selected_companies"
when you will find the parameter, everything will be understood well....