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.
Related
I want to add an order_number to my reservations. Now everytime an order gets created I want to change the value of the order_number.
I tried #reservation.order_number = 1000 and then #reservation.order_number += 1, but I soon realised that this doesn't make any sense.
Here is my create method from my reservations controller:
def create
service = Service.find(params[:service_id])
if current_user.admin?
flash[:alert] = "Du kannst nicht dein eigenes Angebot kaufen"
elsif current_user.stripe_id.blank?
flash[:alert] = "Füge eine Zahlungsmehtode hinzu"
return redirect_to payment_method_path
else
#reservation = current_user.reservations.build
#reservation.service = service
#reservation.price = service.price
#reservation.order_number = 1000
if #reservation.Bearbeitung!
flash[:notice] = "Ihre Anfrage wurde erfolgreich versendet"
ReservationMailer.confirm_email_to_guest(#reservation.user, service).deliver
confirm_sms(service, #reservation)
else
charge(service, #reservation)
end
end
redirect_to submit_reservation_path(#reservation)
end
in your model you can do something like,
before_save :add_order_number
private
def add_order_number
default_order_number = 1000
previous_order = Order.last
if previous_order
puts "last order_number was #{previous_order.order_number}"
self.order_number = previous_order.order_number + 1
else
puts "there was no last number, setting order number to default_order_number"
self.order_number = default_order_number
end
end
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.
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
I am getting this error, I don't know what happened, it's been working fine few days before but it's not working now. This is the code:
#containerformat = Containerformat.new(params[:containerformat])
if #containerformat.containerFmt == 'TS'
#containerformat = Containerformat.new(params[:containerformat])
#transportstream =
#containerformat.transportstreams.build(params[:transportstream])
#transportstream.save
#program = #transportstream.programs.build(params[:program])
#program.save
#user = #containerformat.users.build(params[:user])
#user.save
if params[:videoCodec_id]!= nil
#stream = #program.streams.build(params[:stream])
#stream.videocodec = Videocodec.find(#stream.videoCodec_id)
#stream.save
end
if params[:audioCodec_id]!= nil
#stream = #program.streams.build(params[:stream])
#stream.audiocodec = Audiocodec.find(#stream.audioCodec_id)
#stream.save
end
end
if #containerformat.containerFmt == 'PS'
#programstream =
#containerformat.programstreams.build(params[:programstream])
#subtitle = #programstream.subtitles.build(params[:subtitle])
#subtitle.save
#programstream.save
#stream = #programstream.streams.build(params[:stream])
#user = #containerformat.users.build(params[:user])
#user.save
if params[:videoCodec_id]!= nil
#stream = #programstream.streams.build(params[:stream])
#stream.videocodec = Videocodec.find(#stream.videoCodec_id)
#stream.save
end
if params[:audioCodec_id]!= nil
#stream = #programstream.streams.build(params[:stream])
#stream.audiocodec = Audiocodec.find(#stream.audioCodec_id)
#stream.save
end
end
if #containerformat.containerFmt == 'YUV'
#yuvstream = #containerformat.yuvstreams.build(params[:avistream])
##subtitle = #yuvstream.subtitles.build(params[:subtitle])
##subtitle.save
#yuvstream.save
#stream = #yuvstream.streams.build(params[:stream])
#user = #containerformat.users.build(params[:user])
#user.save
if params[:videoCodec_id]!= nil
##stream = #programstream.streams.build(params[:stream])
##stream.videocodec = Videocodec.find(#stream.videoCodec_id)
##stream.save
end
if params[:audioCodec_id]!= nil
##stream = #programstream.streams.build(params[:stream])
##stream.audiocodec = Audiocodec.find(#stream.audioCodec_id)
##stream.save
end
end
if #containerformat.containerFmt == 'AVI'
#avistream = #containerformat.avistreams.build(params[:avistream])
#avistream.save
#stream = #avistream.streams.build(params[:stream])
#user = #containerformat.users.build(params[:user])
#user.save
if params[:videoCodec_id]!= nil
#stream = #avistream.streams.build(params[:stream])
#stream.videocodec = Videocodec.find(#stream.videoCodec_id)
#stream.save
end
if params[:audioCodec_id]!= nil
#stream = #avistream.streams.build(params[:stream])
#stream.audiocodec = Audiocodec.find(#stream.audioCodec_id)
#stream.save
end
end
I have yuvstreams as table in my database like other tables avisteams, programstreams table.
You need a has_many :yuvstreams in your Containerformat class.
This defines the relationship between containerformats and yuvstreams from the containerformat point of view. You can find more details in the api docs for the has_many method. Basically though, without that you can't refer to yuvstreams from a containerformat.
One additional point on style. Typically rails uses an _ and camel case to make names more readable. So you would have YuvStream and ContainerFormat as your class name and has_many :yuv_streams as your association definition. Rails expects this kind of naming and can sometimes make educated guesses about things if you use it.
Could anyone help with this problem:
Upon "create", the user is redirected to the url: model/model_id (eg post/1), instead I am redirected to models/url_encoding_object (eg posts/.%23) and there is an "406 Not Acceptable" message in the console.
Typically, upon create, the console's message is "Processing PostsController#create (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]", but with this error, the message is "Processing PostsController#create to # (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]"
I've seen austinfromboston's response and tried his "old fashioned but effective" solution to that similar problem, but it doesn't work for me.
Any help would be greatly appreciated
Controller Code:
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ?
#group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area &&
#group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
# unless #user.is_in_group?(#group)
# #user.memberships << #group
# end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(group_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
Looks like either your routes are off somewhere or your model_id parameter is not what you are expecting. Might want to check to see what that parameter is being set to.
It's also really hard to give any suggestions without seeing controller code. Can you post the method making this call?
There's a lot of superfluous code, in your controller. It still works, but you're doing a lot of things the hard way.
Your problem is this line:
format.html { redirect_to(groups_path(#group.id)) }
Which redirects to the collective groups url adding the parameter #group.id.
What it should be is
format.html { redirect_to(group_path(#group.id)) }
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ? #group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area && #group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
unless #user.is_in_group?(#group)
#user.memberships << #group
end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(groups_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
What is this .1 doing at the end of the line??
flash[:notice] = :group_was_successfully_created.l
I tried to run similar code in my environment and it choked on that.
It should also reference:
group_path(id)
not
groups_path(id)