Why Importing gmail contacts using Omnicontacts takes only 99 contacts - ruby-on-rails

I am using omnicontacts to import contacts from gmail. But It takes only 99 contacts not all.
Here is my code
def contacts_callback
#contacts = request.env['omnicontacts.contacts']
#contacts.each do |contact|
contact1 = current_user.contacts.new
contact1.name = contact[:name]
contact1.email = contact[:email]
contact1.group = "Others"
contact1.save(:validate => false)
end
redirect_to "/contact"
end
I can't figure out problem. Please help.

You need to add the max_contacts option in your initializer:
importer :gmail, "xxx", "yyy", :max_results => 1000
I have just updated the README to include this.

Solved it :)
I went to lib/omnicontacts/importer/gmail.rb
def initialize *args
super *args
#auth_host = "accounts.google.com"
#authorize_path = "/o/oauth2/auth"
#auth_token_path = "/o/oauth2/token"
#scope = "https://www.google.com/m8/feeds"
#contacts_host = "www.google.com"
#contacts_path = "/m8/feeds/contacts/default/full"
#max_results = (args[3] && args[3][:max_results]) || 100
end
And I just change #max_results 100 to 500. Now its working

Related

how append an object to association relation in rails?

In a rails 4.1 application I need to add an object to an "AssociationRelation"
def index
employee = Employee.where(id_person: params[:id_person]).take
receipts_t = employee.receipts.where(:consent => true) #gives 3 results
receipts_n = employee.receipts.where(:consent => nil).limit(1) #gives 1 result
#I would need to add the null consent query result to the true consent results
#something similar to this and the result is still an association relation
#receipts = receipts_t + receipts_n
end
Is there a simple way to do this?
A way of solving this:
def index
employee_receipts = Employee.find_by(id_person: params[:id_person]).receipts
receipts_t = employee_receipts.where(consent: true)
receipts_n = employee_receipts.where(consent: nil).limit(1)
#receipts = Receipt.where(id: receipts_t.ids + receipts_n.ids)
end
Unfortunately .or() can't be used here because it's only available from Rails v5.0.0.1
you could do this way
receipts_t_ids = employee.receipts.where(:consent => true).pluck(:id)
receipts_n_ids = employee.receipts.where(:consent => nil).limit(1).pluck(:id)
#receipts = Receipt.where(id: receipts_t_ids + receipts_n_ids)
To avoid extra queries and keeping arrays in memory, you can use or
Like this:
def index
employee_receipts = Employee.find_by(id_person: params[:id_person]).receipts
#receipts =
employee_receipts.where(consent: true).or(
employee_receipts.where(consent: nil).limit(1)
)
end

Get Input from form for API url Request in rails?

I'm new to Rails and I'm trying to make a simple weather API to get weather by zipcode
is there a way to get the zipcode from user input from a simple form, this will be just for learning so I'm not trying to make users devise, or users model
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip=#{zipcode}&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
actually I figured it out, i needed to add
def zipcode
#zip_query = params[:zipcode]
if params[:zipcode] == ""
#zip_query = "Hey you forgot to enter a zipcode!"
elsif params[:zipcode]
# Do Api stuff
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip='+ #zip_query +'&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
#name = #output['name']
# Check for empty return result
if #output.empty?
#final_output = "Error"
elsif !#output
#final_output = "Error"
else
#final_output = ((#output['main']['temp'] - 273.15) * 9/5 +32).round(2)
end
end
end
in the controller.rb file
and add
post "zipcode" => 'home#zipcode'
get "home/zipcode"
in the routes file
but I'm sure this is not the best practice

How to get OpenStreetMap access token with devise omniauth-osm

In my controller, I'm trying to get an access token to OSM.
class Auth::OauthController < Devise::OmniauthCallbacksController
def osm
#user = AppUser.from_omniauth(request.env["omniauth.auth"])
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
sign_in_and_redirect #user
end
end
When I get the access token and writes it to the database.
Next, I try to use the OSM API through oauth gem.
#consumer=OAuth::Consumer.new Settings.osm.consumer_key,
Settings.osm.consumer_secret,
{site: osm_uri}
#access_token = OAuth::AccessToken.new(#consumer, current_user.token, current_user.token_secret)
puts #access_token.get('/api/0.6/user/preferences').body
However, this code does not work in the console I see the authorization error
the error in this code:
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
correct code
#app_user.token = request.env["omniauth.auth"]['credentials']['token']
#app_user.token_secret = request.env["omniauth.auth"]['credentials']['secret']

Ruby on Rails - Import CSV file

I'm following this tutorial CSV-FILE-EXPORT-IMPORT-RAILS but something im doing wrong, because i got an silly error when i'm trying to create my object uninitialized constant CuentaContablesController::False. I can read the file without problem, but this error is giving me an headache! Any help will be appreciated!
The method for import in my controller(cuenta_contable_controller.rb) looks like this;
class CuentaContablesController < ApplicationController
....
def upload(params)
logger.info "**File loaded***"
infile = params[:file].read
n, errs = 0, []
#archivo = []
SV.parse(infile) do |row|
n += 1
# SKIP: header i.e. first row OR blank row
next if n == 1 or row.join.blank?
cuenta_contable = CuentaContable.build_from_csv(row)
if cuenta_contable.valid?
cuenta_contable.save
#archivo << row
else
errs << row
end
end
logger.info errs
flash[:success] = "Las cuentas contables fueron cargadas."
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #archivo }
end
end
And my model(cuenta_contable.rb) like this
class CuentaContable < ActiveRecord::Base
....
def self.build_from_csv(row)
ultimo_nivel = (row[5].downcase=="si") ? (True):(False)
#cuenta = find_or_initialize_by_cuenta("#{row[0]}-#{row[1]}-#{row[2]}")
# Buscas el archivo existing customer from email or create new
cuenta = CuentaContable.new(:cuenta => "#{row[0]}-#{row[1]}-#{row[2]}",
:descripcion => "#{row[3].titleize}",
:categoria_cuenta => "#{row[4].titleize}",
:ultimo_nivel=> ultimo_nivel)
return cuenta
end
You're using True instead of true (likewise for false).
But neither are necessary; the ternary is superfluous and over-parenthesized:
# Ick!
ultimo_nivel = (row[5].downcase=="si") ? (True):(False)
# Pretty!
ultimo_nivel = row[5].downcase == "si"
You might even use a helper to turn row 5 into a boolean and remove it from the mainline code.

Gem Resque Error - Undefined "method perform" after Overriding it form the super class

First of all Thanks for you all for helping programmers like me with your valuable inputs in solving day to day issues.
This is my first question in stack overflow as I am experiencing this problems from almost one week.
WE are building a crawler which crawls the specific websites and extract the contents from it, we are using mechanize to acheive this , as it was taking loads of time we decided to run the crawling process as a background task using resque with redis gem , but while sending the process to background I am experiencing the error as the title saying,
my code in lib/parsers/home.rb
require 'resque'
require File.dirname(__FILE__)+"/../index"
class Home < Index
Resque.enqueue(Index , :page )
def self.perform(page)
super (page)
search_form = page.form_with :name=>"frmAgent"
resuts_page = search_form.submit
total_entries = resuts_page.parser.xpath('//*[#id="PagingTable"]/tr[2]/td[2]').text
if total_entries =~ /(\d+)\s*$/
total_entries = $1
else
total_entries = "unknown"
end
start_res_idx = 1
while true
puts "Found #{total_entries} entries"
detail_links = resuts_page.parser.xpath('//*[#id="MainTable"]/tr/td/a')
detail_links.each do |d_link|
if d_link.attribute("class")
next
else
data_page = #agent.get d_link.attribute("href")
fields = get_fields_from_page data_page
save_result_page page.uri.to_s, fields
#break
end
end
site_done
rescue Exception => e
puts "error: #{e}"
end
end
and the superclass in lib/index.rb is
require 'resque'
require 'mechanize'
require 'mechanize/form'
class Index
#queue = :Index_queue
def initialize(site)
#site = site
#agent = Mechanize.new
#agent.user_agent = Mechanize::AGENT_ALIASES['Windows Mozilla']
#agent.follow_meta_refresh = true
#rows_parsed = 0
#rows_total = 0
rescue Exception => e
log "Unable to login: #{e.message}"
end
def run
log "Parsing..."
url = "unknown"
if #site.url
url = #site.url
log "Opening #{url} as a data page"
#page = #agent.get(url)
#perform method should be override in subclasses
#data = self.perform(#page)
else
#some sites do not have "datapage" URL
#for example after login you're already on your very own datapage
#this is to be addressed in 'perform' method of subclass
#data = self.perform(nil)
end
rescue Exception=>e
puts "Failed to parse URL '#{url}', exception=>"+e.message
set_site_status("error "+e.message)
end
#overriding method
def self.perform(page)
end
def save_result_page(url, result_params)
result = Result.find_by_sql(["select * from results where site_id = ? AND ref_code = ?", #site.id, utf8(result_params[:ref_code])]).first
if result.nil?
result_params[:site_id] = #site.id
result_params[:time_crawled] = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result_params[:link] = url
result = Result.create result_params
else
result.result_fields.each do |f|
f.delete
end
result.link = url
result.time_crawled = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result.html = result_params[:html]
fields = []
result_params[:result_fields_attributes].each do |f|
fields.push ResultField.new(f)
end
result.result_fields = fields
result.save
end
#rows_parsed +=1
msg = "Saved #{#rows_parsed}"
msg +=" of #{#rows_total}" if #rows_total.to_i > 0
log msg
return result
end
end
What's Wrong with this code?
Thanks

Resources