- 1
- 2
- 3
def self.get_fio(l_name, f_name, s_name)
"#{l_name} #{f_name} #{s_name}"
end
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−109
def self.get_fio(l_name, f_name, s_name)
"#{l_name} #{f_name} #{s_name}"
end
В модели User
−99
if params[:back_url].try(:start_with?, '/appeals/') && params[:back_url].try(:end_with?, '/next_step')
Регулярки для лохов
−122
def contract_params
if params[:contract][:contract_type].to_i == 1
field = :contractor_id
else
field = :legal_entity_id
end
params.require(:contract).permit(
:contract_type,
:paid_expectation,
field
)
end
Much strong, very params.
−126
= simple_fields_for @med_program_template do |f|
- form ||= f # Страшное коварство
−141
# GET /med_programs/1/edit
def edit
@med_program = MedProgram.includes(:appeal, :template).find(params[:id])
next_step_path = next_step_appeal_path(@med_program.appeal_id)
# TODO: flash.keep ?
case true
when @med_program.appeal.kit_not_found?
redirect_to @med_program.appeal
when @med_program.appeal.new?
# Just render edit view
when @med_program.appeal.verify_person?
redirect_to edit_person_path(@med_program.appeal.person_id, :back_url => next_step_path)
return # для наглядности
when @med_program.appeal.create_user?
if @med_program.appeal.person.user_id
path = edit_user_path(@med_program.appeal.person.user_id, :back_url => next_step_path)
else
path = new_user_path(:person_id => @med_program.appeal.person_id, :back_url => next_step_path)
end
redirect_to path
return # для наглядности
when @med_program.appeal.add_doctor?
redirect_to add_doctor_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.create_user_doctor?
if @med_program.doctor.person.user_id
path = edit_user_path(@med_program.doctor.person.user_id, :back_url => next_step_path)
else
path = new_user_path(:person_id => @med_program.doctor.person_id, :back_url => next_step_path)
end
redirect_to path
return # для наглядности
when @med_program.appeal.add_contractor?
redirect_to add_contractor_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.input_settings?
redirect_to set_settings_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.pick_specialists?
redirect_to select_specialists_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.pick_operators?
redirect_to select_operators_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.read_informed_consent?
redirect_to informed_consent_med_program_path(@med_program.id)
return # для наглядности
when @med_program.appeal.sign_contract?
redirect_to sign_contract_med_program_path(@med_program.id)
return # для наглядности
else
redirect_to @med_program
end
end
Самый наглядный код в мире
−157
patient_id = MedProgram.where(:id => params[:med_program_id]).limit(1).pluck(:patient_id).first
−99
def append_card(cards, new_card)
if cards.nil?
new_card == GameEvent::YELLOW_CARD ? 'yellow' : 'red'
elsif cards == 'yellow'
new_card == GameEvent::YELLOW_CARD ? 'two_yellow' : 'yellow_red'
elsif cards == 'red'
new_card == GameEvent::YELLOW_CARD ? 'yellow_red' : 'red'
elsif cards == 'two_yellow'
'two_yellow'
elsif cards == 'yellow_red'
new_card == GameEvent::YELLOW_CARD ? 'two_yellow' : 'yellow_red'
end
end
ничего особенного, просто подсчитываем, какую карточку получил игрок футбольной команды.
а я думал, что что-то понимаю в футболе... я никогда в жизни так не ошибался
−89
# Да, да, захардкоженные id!
# .where(id: [id_arrays]) ? Не, не слышал
@cities = [52, 21, 9, 18, 196, 27, 106, 4, 40, 71].collect { |c| City.find(c) }
# Это все в одном экшене, ага.
session[:latitude] = params[:my_latitude]
session[:longitude] = params[:my_longitude]
session[:my_address] = params[:my_address]
session[:fuel] = params[:fuel][:fuel_id]
session[:range] = params[:station][:range]
# А потом кто-нибудь развернет базу из бэкапа без сохранения первичных ключей и все перестанет работать.
@fuels = Fuel.where(:id=>[1, 2, 3, 5])
# Типичный экшен
session[:view_sub_page] = action_name
id = params[:station_chain].split("-")
s_id = id[id.size - 2]
station = Station.where(:id=>s_id)
@fuels_level = AppUtils.calculate_price(station)
@prices = station.last.prices.order("created_at").group_by { |item| item.fuel_id }
@fuel_id = id[id.size - 1].to_i
@station_lists = Station.get_station_detail_map(station, @fuels_level, @fuel_id, @prices)
@station = station.last
@station_logo = ''
@station_logo_chain = ManageStationChain.where(:brand_id=>@station.brand_id).last
@station_logo = PromoLogo.find_by_station_id(@station.id)
@end = @station.address
@fuels = Fuel.where(:id=>[1, 2, 3, 5])
@sub_station = ""
@cities = Station.get_static_cities()
# Какие еще Rails, у меня свой лисопед
def City.find_by_name(name)
city = City.where("name = ?", name).first
if city.nil?
city = City.new
city.name = name
city.save
end
return city
end
# Именно так, в одну строчку. station.open_time и close_time - типа :time в базе
if !station.open_time.nil? and !station.close_time.nil? and (Time.parse(station.open_time.to_s)...Time.parse(station.close_time.to_s)).cover?(Time.now.utc.change(year: 2000, month: 1, day: 1, hour: Time.now.hour, min: Time.now.min, second: 0)) == false
return "PRICE_LEVEL_CLOSE"
end
# Компьютер купил, программировать не купил
# В таблице Points - тысячи записей
def get_points
points = Points.all
render json: {:success => true, :data => {:points => points.as_json(:only => [:action, :points, :points_new])}} and return
end
# И под занавес - код логина
# Гемы? Devise? OAuth? А чой энта?
def login
register = false
url = "https://graph.facebook.com/me/?access_token="+params[:facebook_token]
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.path + "?" + uri.query)
response = http.request(request)
if response.code == "200"
facebook_response = JSON.parse(response.body)
user = User.where("facebook_id = ?", facebook_response["id"]).first
if !user
user = User.new
user.facebook_id = facebook_response["id"]
user.nick = facebook_response["username"]
user.email = facebook_response["email"]
register = true
end
user.email = facebook_response["email"]
user.generate_token
user.save
if register == true
history = History.new
history.user = user
points = Points.where(:action => "REGISTER").first
history.points_action = points
history.points = points.points
user.points+=points.points
user.save
history.save
end
logger.debug("Calculating point");
points = Points.where('action != ?', 'FACEBOOK_INVITES')
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
logger.debug("Testing for points");
logger.debug(points.as_json(:only => [:action, :points]))
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
if user.disabled == true
render json: {:success => false, :error => {:message => "Invalid facebook token", :error_code => "INVALID_TOKEN"}}, status: :unauthorized and return
else
render json: {:success => true, :data => {:auth_token => user.auth_token, :points => points.as_json(:only => [:action, :points])}} and return#
...
Почему никогда нельзя нанимать индусских программистов. Выдержки из избранного.
−82
@old_article_purchase.old_article.warehouse_placement = '102A1'
if @old_article_purchase.old_article.valid?
@old_article_purchase.old_article.save
end
−93
deals = Deal.joins(:deal_locations).select("deals.id, (SELECT array(SELECT category_id FROM deal_categories WHERE deal_id = deals.id ORDER BY category_id ASC)) AS category, deals.start_date, deals.end_date, deals.address, deals.theme, deals.alias, deals.metro, deals.district, deals.discount, deals.coupon_count, deals.issued_coupons, deals.main_image, count(*) OVER() AS total_count, trunc(abs(extract(epoch FROM age(deals.end_date, clock_timestamp()))/86400)) AS days_left").where("deal_locations.deal_id = deals.id AND deal_locations.location_id = ? AND deals.category_id IN (#{categories[0...-2]}) AND deals.id NOT IN (#{ex_deals.map{|e| e}.join(", ")})", params[:location].to_i).active.in_stock.limit(limit).offset(offset).order("deals.start_date desc")
Rails. Да, да, активрекорд, я помню о тебе.