I'm working with koala. I have to check the permission given is granted by user for the application. I have made a helper called facebook helper. There is a def has_permission?(perm). My code follows:
def has_permission? (perm)
#graph = Koala::Facebook::API.new(current_user.token)
#permissions = #graph.get_connections('me', 'permissions')
#bool = false
#permissions.each do |p|
if p[0] == perm && p[1] == 'granted'
#bool = true
break
end
end
return #bool
end
It always returns false. What is wrong with this ?
Is your #permissions getting populated? You can also write this without the break
def has_permission? (perm)
#graph = Koala::Facebook::API.new(current_user.token)
#permissions = #graph.get_connections('me', 'permissions')
#bool = false
#permissions.each do |p|
unless #bool
#bool = (p[0] == perm && p[1] == 'granted')
end
end
#bool
end
I would also move the p[0] == perm && p[1] == 'granted' into its own method for better readability.
I solved it myself:
def has_permission? (perm)
#graph = Koala::Facebook::API.new(current_user.token)
#permissions = #graph.get_connections('me', 'permissions')
# binding.pry
#bool = false
#permissions.each do |p|
if (p['permission'] == perm && p['status'] == 'granted')
#bool = true
break
end
end
#bool
end
Just changed p[0] to p['permission'] and p[1] to p['status']
Related
I have a reports controller where I have leaderboard. I would like to download the leader board into a csv file
here is the leaderboard code
def leaderboard
if params.has_key?(:start_date) && params.has_key?(:end_date) && params.has_key?(:account)
if params[:unit] == 'all'
#start_date = current_user.created_at
#end_date = Time.now
else
#start_date = Time.at(params[:start_date].to_i/1000)
#end_date = Time.at(params[:end_date].to_i/1000)
end
if params[:account] == 'all'
user_accounts = current_user.accounts.collect{ |a| a.id }
ActsAsTenant.without_tenant do
#conversations = Conversation.where(account_id: user_accounts).updated_between(#start_date,#end_date)
#users = current_user.accounts.collect{|account| account.users}.flatten.uniq.to_a
unassigned = User.new(name: 'Un-assigned')
#users << unassigned
end
else
account = Account.find(params[:account])
ActsAsTenant.with_tenant(account) do
#conversations = account.conversations.updated_between(#start_date,#end_date)
#users = account.users.to_a
unassigned = User.new(name: 'Un-assigned')
#users << unassigned
end
end
else
render json: {error: 'Invalid parameters'}, status: 422
end
end
here is the image of the data I want to be able to download as csv
https://i.stack.imgur.com/VI6lo.png
here is the leaderboard.json.jbuider
json.users #users do |user|
json.(user,:id, :name)
json.closed_count #conversations.where(user: user).closed.count
json.open_count #conversations.where(user: user).open.count
json.replies #conversations.where(user: user).inject(0){|sum, conversation| sum + conversation.messages.where(updated_at: #start_date..#end_date).where(direction: 'OUT').count}
json.resolution_time formatted_duration(array_mean(#conversations.closed.where(user: user).closed.collect{ |c| c.resolution_time }))
json.first_response Conversation.first_response(#conversations.where(user: user))
end
json.total_closed #conversations.closed.count
json.total_open #conversations.open.count
json.total_replies #conversations.inject(0){|sum, conversation| sum + conversation.messages.where(updated_at: #start_date..#end_date).where(direction: 'OUT').count}
json.start_date #start_date.to_i * 1000
json.end_date #end_date.to_i * 1000
How do I go about downloading it into a csv?
From your code snippet I'm not sure what you're trying to "export", but in general it should look like:
csv_lines = []
#some_data.each do |record|
csv_lines << "#{record.field1};#{record.field2};#{record.field3}" #and so on
end
#export csv_lines
txt = csv_lines.join "\n"
I have a if else condition in my ruby code listed below:
if !category.nil?
return false unless company_matches.any? { |w|
comparison = /(\s|^)#{w}(\s|$)/i
(title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison)) && (category == 'Business')}
else
return false unless company_matches.any? { |w|
comparison = /(\s|^)#{w}(\s|$)/i
(title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison))}
end
How can i simplify this to make it look more subtle?
company_matches.any? do |company|
[title, description, clean_title, clean_desc].any? do |attribute|
attribute.match? /(\s|^)#{company}(\s|$)/i
end && (category == 'Business' || category.nil?)
end
You can create a method to do your comparisons so you don't repeat yourself. You can also abstract the comparison variable out of the if .. else block. Here's what I have:
comparison = /(\s|^)#{w}(\s|$)/i
result = perform_comparison(title, description, clean_title, clean_desc, comparison)
unless category.nil?
return false unless company_matches.any? { |w| result && (category == 'Business')}
else
return false unless company_matches.any? { |w| result }
end
# somewhere else in your code
def perform_comparison(title, description, clean_title, clean_desc, comparison)
title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison)
end
I have loop that is checking if there is no image display a dummy image. I don't know what is wrong with this loop. It is not display the dummy image.Any help will be appreciated. Thank you
.col-md-12
- #applied_users.each do |user|
.applied
%a
%a.litle-modules.pull-left{href: show_user_public_path(user.id, ((Apply.where user_id: user.id, job_id: #job.id).first).id)}
.col-xs-6.col-md-5
.thumbnail
- if user.image != nil
= image_tag "profile_pic.jpeg"
- elsif user.image.nil?
= image_tag "profile_pic.jpeg"
.col-md-7.pull-right
%h2= user.fname
%p= user.location
%p= user.description
def show_private
#this method is responsible for showing the companies their job application page after matches have been made and after people have applied.
neo_results_array = []
percentage_match = []
#job = Job.find(params[:id])
#neo_results = Neo4jProcess.match_users(#job.id, 20000)
filtered_results = JSON.parse(#neo_results)
users = filtered_results["users"]
users.each do |user|
if user["score"] >= 0.005
neo_results_array << user["user_id"]
percentage_match << user["score"]
else
end
end
#final_array = neo_results_array.zip(percentage_match)
print #final_array
if #job.applies == [] && neo_results_array == []
redirect_to share_page_path(#job.id)
else #job.applies != [] || neo_results_array != []
applied = #job.applies.pluck(:user_id)
#applied_users = User.find(applied)
percentage_user_array = []
#final_array.each do |item|
percentage_user_array << item[0]
end
#matched_users = User.find(percentage_user_array)
end
end
just edited. here you can see my controller responsible for the img and other things
Remove condition from else
If you want to put some conditions for else as well use
elsif user.image.nil?
When an new order_preview is created, I call USPS for shipping options. If a user updates their zip, I would like the ship_option to reset
Edit: I am no longer calling the intial API call from the view, rather I do an after_create method in the controller.
def get_ship_options
ship_options = {}
#order_preview.fedex_rates.each do |k, v|
if k.service_name == "FedEx Ground Home Delivery" || k.service_name == "FedEx 2 Day" || k.service_name == "FedEx Standard Overnight"
ship_options["#{k.service_name}"] = "#{number_to_currency(k.price.to_f / 100)}"
end
end
#order_preview.usps_rates.each do |k, v|
if k.service_name == "USPS Priority Mail 1-Day"
ship_options["#{k.service_name}"] = "#{number_to_currency(k.price.to_f / 100)}"
end
end
#order_preview.ship_option_hash = ship_options.map { |k,v| ["#{k} - #{v}","#{k} - #{v}" ] }
#order_preview.save
end
I tried using the answers you guys provided, but the before_save didn't actually save the shiphash the way #order_preview.save does at the end of the above method.
I tried using the same idea, but zip_changed? doesn't work in the controller.
How can I save the new hash that is pulled from the model directly over to the #order_preview ?
From the model I now have
Model.rb
def clear_hash
if zip_changed?
get_shipping_rates
end
end
and
ship_options = {}
fedex_rates.each do |k, v|
if k.service_name == "FedEx Ground Home Delivery" || k.service_name == "FedEx 2 Day" || k.service_name == "FedEx Standard Overnight"
ship_options["#{k.service_name}"] = "#{number_to_currency(k.price.to_f / 100)}"
end
end
usps_rates.each do |k, v|
if k.service_name == "USPS Priority Mail 1-Day"
ship_options["#{k.service_name}"] = "#{number_to_currency(k.price.to_f / 100)}"
end
end
ship_option_hash = ship_options.map { |k,v| ["#{k} - #{v}","#{k} - #{v}" ] }
**save ship_option_hash to #order_preview.ship_option_hash**
class OrderPreview
before_save :check_state
def check_state
if zip_changed?
ship_option_hash = nil
end
end
...
end
class OrderPreviewController
def update
#order_preview.update(order_preview_params)
end
...
end
Try changing your callback from after_save to before_save. Record considered changed until the changes are not persisted. Changes are lost when you save your object, that's why your record is unchanged when you check for changes in after_save callback.
It should work this way:
before_save :clear_hash, if: :zip_changed?
def clear_hash
ship_option_hash = nil
end
This way the changes will be saved, because you use before_save. In your code, changes were not saved, because you used after_save callback
You controller:
def update
respond_to do |format|
if #order_preview.update(order_preview_params)
flash[:notice] = "Record was successfully updated"
else
flash[:alert] = "Record was not updated"
end
end
end
I'm trying to display unique IPS alerts for my dashboard. If I display #filtered_snort_detail_query I get loads of alerts, and many could be ignored since alerts are packet based and one attack can generate 100's or 1000's of alerts. No need to display all of them. I'm trying to use scan to find the sig ID, source IP, and destination IP.
When it's all said and done, I'm looking to display #snort_dash_info in my view vs. #filtered_snort_detail_query
My error:
undefined method `scan' for #<Hash:0x007f088a7a4830>
app/controllers/csdashboard_controller.rb:139:in `block in index'
app/controllers/csdashboard_controller.rb:138:in `each'
app/controllers/csdashboard_controller.rb:138:in `index'
Code from the controller (Line 139 starts with sid_data):
if #es_snort_detail_query.count > 0
#filtered_snort_detail_query = Array.new
#es_snort_detail_query.each do |ips_detail|
next if ips_detail['_source']['type'] != 'snort-ips'
next if ips_detail['_source']['#timestamp'] < #ts
#filtered_snort_detail_query.push(ips_detail)
end
if #filtered_snort_detail_query.count > 0
#snort_dash_info = Array.new
sid = Array.new
ip_src = Array.new
ip_dst = Array.new
#filtered_snort_detail_query.each do |ips_alerts|
sid_data = ips_alerts.scan(/\[\d+:\d+:\d+\]/)
src_ip_data = ips_alerts.scan(/(?:[0-9]{1,3}\.){3}[0-9]{1,3}/)
dst_ip_data = ips_alerts.scan(/(?:[0-9]{1,3}\.){3}[0-9]{1,3}/)
sid.push(sid_data[0]) unless sid_data[0].nil?
ip_src.push(src_ip_data[0]) unless src_ip_data[0].nil?
ip_dst.push(dst_ip_data[1]) unless dst_ip_data[1].nil?
snort_details = [{:ips_info => sid},{:ips_info => ip_src}, {:ips_info => ip_dst}]
snort_details_info = snort_details.uniq do |show_me|
show_me[:ips_info]
end
#snort_dash_info.push(snort_details_info)
end
end
end
Use each_pair like:
ips_alerts.each_pair { |k, v| puts "#{k} #{v}" }
So in order to get what you want, try:
ips_alerts.each_pair do |k, v|
if k == "sid_data" # pure assumption on my part
sid_data = v.scan(/(?:[0-9]{1,3}\.){3}[0-9]{1,3}/)
end
end
Sorry I can't think of a prettier way but it works.
Got it some what working, so I guess this question should be done. I'm not getting the undefined method for scan anymore, and I've verified that my unique_ids are working. The only issue is I'm now displaying the unique_ids and not using them to remove duplicate alerts. That's for another question I guess..
Code:
if #es_snort_detail_query.count > 0
sid = Array.new
ip_src = Array.new
ip_dst = Array.new
#snort_dash_info = Array.new
#es_snort_detail_query.each do |ips_detail|
next if ips_detail['_source']['type'] != 'snort-ips'
next if ips_detail['_source']['#timestamp'] < #ts
if ips_detail['_source']['message'].nil?
text_msg = ips_detail['_source']['message']
else
text_msg = ips_detail['_source']['message']
end
unless text_msg.nil?
sid_data = text_msg.scan(/\[\d+:\d+:\d+\]/)
src_ip_data = text_msg.scan(/(?:[0-9]{1,3}\.){3}[0-9]{1,3}/)
dst_ip_data = text_msg.scan(/(?:[0-9]{1,3}\.){3}[0-9]{1,3}/)
sid.push(sid_data[0]) unless sid_data[0].nil?
ip_src.push(src_ip_data[0]) unless src_ip_data[0].nil?
ip_dst.push(dst_ip_data[1]) unless dst_ip_data[1].nil?
unique_ids = [{:ips_info => sid},{:ips_info => ip_src}, {:ips_info => ip_dst}]
snort_details_info = unique_ids.uniq do |show_me|
show_me[:ips_info]
end
#snort_dash_info.push(snort_details_info)
end
end
end