Last active
February 24, 2018 05:09
Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rake db:drop db:create db:migrate RAILS_ENV=test; | |
rake db:drop RAILS_ENV=test; | |
rake db:create db:migrate RAILS_ENV=test; | |
rake db:drop | |
rake db:create db:migrate | |
rake db:create db:structure:load db:migrate db:seed RAILS_ENV=test; | |
rake db:create db:structure:load db:migrate db:seed | |
rake db:drop | |
rake db:create db:structure:load db:migrate db:seed RAILS_ENV=test; | |
rake db:create db:migrate db:seed | |
rake db:create db:migrate db:seed RAILS_ENV=test; | |
rake db:create db:migrate RAILS_ENV=test; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
result = search(TYPE, { | |
query: { | |
bool: { | |
must: [ | |
{ | |
multi_match: { | |
query: query, | |
fields: fields, | |
}, | |
}, | |
{ match: { search_clicks_user_ids: user.id } }, | |
], | |
minimum_should_match: 1, | |
boost: 2.0, | |
}, | |
}, | |
}) | |
result = search(TYPE, { | |
query: { | |
match_all: { boost: 1.2 } | |
} | |
}) | |
result = search(TYPE, { | |
from: 0, | |
size: LIMIT, | |
query: { | |
function_score: { | |
query: { | |
bool: { | |
must: [{ | |
multi_match: { | |
query: query, | |
fields: fields_trigram, | |
} | |
}] | |
} | |
}, | |
score_mode: "sum", | |
boost_mode: "sum", | |
functions: [ | |
# Add score for matches using full words | |
{ | |
filter: { | |
multi_match: { query: query, fields: fields } | |
}, | |
weight: 200, | |
}, | |
# Search terms located near each other | |
# (e.g. not far than 30 words between) | |
# are more important than the same found separately. | |
{ | |
filter: { | |
multi_match: { | |
query: query, | |
fields: fields, | |
type: "phrase", | |
slop: 30 | |
}, | |
}, | |
weight: 100, | |
}, | |
# Score for fields high | |
{ | |
filter: { | |
multi_match: { query: query, fields: wrap_trigram("username") } | |
}, | |
weight: 150, | |
}, | |
{ | |
filter: { | |
multi_match: { query: query, fields: wrap_trigram("full_name") } | |
}, | |
weight: 150, | |
}, | |
{ | |
filter: { | |
multi_match: { query: query, fields: wrap_trigram("url") } | |
}, | |
weight: 150, | |
}, | |
], | |
} | |
}, | |
sort: [ | |
"_score", | |
{ updated_at: { order: "desc" } } | |
] | |
}) | |
Outfit.client_search({ query: { } }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem pristine --all |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem install hanami | |
hanami new bookshelf | |
hanami new bookshelf --database=postgres | |
hanami server | |
hanami console | |
hanami spec | |
bundle exec rake | |
bundle exec hanami db prepare | |
HANAMI_ENV=test bundle exec hanami db prepare |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bundle exec rake assets:precompile RAILS_ENV=production RAILS_GROUPS=assets |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.configuration.value | |
constantize | |
# string to class | |
constantize | |
# logger | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
class Proc | |
def self.compose(f, g) | |
lambda { |*args| f[g[*args]] } | |
end | |
def *(g) | |
Proc.compose(self, g) | |
end | |
end | |
# ENV.fetch("PUMA_WORKER_KILLER_RAM") { 1024 }.to_i | |
# meta should not use | |
def meta(options = {}) | |
return nil if defined?(@@explain).nil? | |
{ explain: @@explain[_model.id.to_s] } | |
end | |
# reduce example | |
result.dig("hits", "hits").reduce({}) do |acc, object| | |
acc[object["_id"]] = object["_explanation"] || [] | |
acc | |
end | |
# NOTE Styled | |
# хорошо | |
[0, 1, 2, 3].each do |item| | |
next unless item > 1 | |
puts item | |
end | |
# хорошо | |
:some_sym1 | |
# хорошо | |
def foo | |
# здесь реализуется основная логика | |
rescue | |
# здесь происходит обработка ошибок | |
end | |
# FILE | |
f = File.open('testfile') | |
begin | |
# некоторые действия над файлом | |
rescue | |
# обработка ошибок | |
ensure | |
f.close unless f.nil? | |
end | |
# Используйте TODO, чтобы пометить отсутствующие возможности или функционал, которые должны быть добавлены позже. | |
# Используйте FIXME, чтобы пометить код с ошибками, который должен быть исправлен. | |
# Используйте OPTIMIZE, чтобы пометить медленный или неэффективный код, который может вызвать проблемы с производительностью. | |
# Используйте HACK, чтобы пометить код "с душком", который должен быть переработан и использует сомнительные практики разработки. | |
# Используйте REVIEW, чтобы пометить все, что должно быть проверено на работоспособность. | |
# Избегайте переменных класса (@@) из-за их "непристойного" поведения при наследовании. | |
def logging(text) | |
path = Rails.root.join('log/log.log') | |
file = File.open(path, "a+") | |
file.puts(text) | |
file.close unless file.nil? | |
end | |
# NOTE get dublicate | |
models.pluck(:id).group_by(&:itself).select { |k, v| v.size > 1 }.map(&:first) | |
Rails.logger.info( | |
"Elasticsearch::Transport::Transport::Errors::NotFound " \ | |
"blogger_user_search_results with id #{1111}" | |
) | |
# Проверить наличие остатка | |
2.0 / 5.0 % 1 == 0 | |
# zsh rake correct | |
hr rake release_second_staging\[100\] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# order | |
class DbTool | |
extend ActiveRecord::ConnectionAdapters::Quoting | |
end | |
quote_ids = DbTool.quote_string(ids.join(',')) | |
MODEL.where(id: ids).order("position(',' || id::text || ',' in ',#{quote_ids},')") | |
outfit.products.select(:id, :title, :retailer_link).map(&:attributes) | |
outfits.find { |outfit| outfit_similiar?(outfit) } | |
outfits.find_each do |outfit| | |
return outfit if outfit_similiar?(outfit) | |
end | |
# NOTE records | |
Truck.exists? | |
# query | |
where('user_id in (select id from bloggers where is_blacklisted)') | |
joins( | |
"LEFT OUTER JOIN search_clicks ON search_clicks.person_id = bloggers.id AND search_clicks.person_type = 'Blogger'" | |
).group(:id).order('COUNT(search_clicks.id) DESC').limit(limit) | |
joins(:search_clicks).order('search_clicks.updated_at DESC').limit(10).map(&:id) | |
where(featured_list_id: id).update_all(["rank=rank+#{offset}"]) | |
# PG order | |
quote_ids = DbTool.quote_string(ids.join(',')) | |
Blogger.where(id: result[:ids]).order("position(',' || id::text || ',' in ',#{quote_ids},')") | |
group_by(&:id) | |
group_by(&:itself) | |
def self.scope(options={}) | |
include = options[:include] | |
model_id = options[:model_id] | |
tag_ids = options[:tag_ids] | |
per_page = options[:per_page] | |
page = options[:page] | |
scope = Model.includes(include).published | |
scope = scope.where(model_id: model_id) if model_id.present? | |
scope = scope.order('published_at desc') | |
scope = scope.paginate(page: page, per_page: per_page) | |
end | |
@product.updated_at = DateTime.now & @product.save == @product.touch(:updated_at) | |
default_scope where(nullified: false) # плохо! | |
default_scope { where(nullified: false) } # хорошо | |
Product.joins(:documents, :files, :etc).where(...).pluck('documents.type') | |
class Location < ActiveRecord::Base | |
has_many :moveable_locations, dependent: :destroy | |
with_options :through => :moveable_locations, :source => :moveable do |location| | |
has_many :trains, source_type: 'Train' | |
has_many :ships, source_type: 'Ship' | |
has_many :copters, source_type: 'Copter' | |
has_many :trucks, source_type: 'Truck' | |
end | |
end | |
------------ | |
Почему-то многие уверены что order на Relation не зависит от того, по какому столбцу мы сортируем. Разновидностью этого заблуждения является отсутствие понимания разницы между order Relation и order Array. Из-за этого можно встретить default_scope с ордером по VARCHAR полю и вопросы в духе: «А почему это у вас так медленно страница загружается? Там же всего пара записей извлекается из БД!». Проблема здесь в том, что дефолтная сортировка — это чертовски дорого, если у нас нет индекса на этом столбце. По умолчанию AR сортирует по pk. Это происходит когда мы делаем | |
Products.first | |
Но у pk есть индекс практически всегда и проблем нет. А вот когда мы говорим, что будет делать order(:name) при любом обращении к модели — начинаются проблемы. | |
Для справки: если объяснять «на пальцах», то при сортировке по индексированному столбцу реальной сортировки не происходит, она уже присутствует в базе и данные сразу отдаются в правильном порядке. | |
------------ | |
# Ограничения | |
Индексы полезны для многих приложений, однако на их использование накладываются ограничения. Возьмём такой запрос SQL: | |
SELECT first_name FROM people WHERE last_name = 'Франкенштейн';. | |
Для выполнения такого запроса без индекса СУБД должна проверить поле last_name в каждой строке таблицы (этот механизм известен как «полный перебор» или «полное сканирование таблицы», в плане может отображаться словом NATURAL). При использовании индекса СУБД просто проходит по B-дереву, пока не найдёт запись «Франкенштейн». Такой проход требует гораздо меньше ресурсов, чем полный перебор таблицы. | |
Теперь возьмём такой запрос: | |
SELECT email_address FROM customers WHERE email_address LIKE '%@yahoo.com';. | |
Этот запрос должен нам найти всех клиентов, у которых е-мейл заканчивается на @yahoo.com, однако даже если по столбцу email_address есть индекс, СУБД всё равно будет использовать полный перебор таблицы. Это связано с тем, что индексы строятся в предположении, что слова/символы идут слева направо. Использование символа подстановки в начале условия поиска исключает для СУБД возможность использования поиска по B-дереву. Эта проблема может быть решена созданием дополнительного индекса по выражению reverse(email_address) и формированием запроса вида: | |
SELECT email_address FROM customers WHERE reverse(email_address) LIKE reverse('%@yahoo.com');. | |
В данном случае символ подстановки окажется в самой правой позиции (moc.oohay@%), что не исключает использование индекса по reverse(email_address). | |
---------------- | |
scope :tables, -> { | |
where(table: ["products", "clients", "images"]) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
expect(logger).to receive(:account_opened).exactly(3).times | |
allow(EM).to receive(:run).and_yield do | |
expect(S3Uploader::GenerateCsv).to receive(:call).with(client_id: client.id).and_return(double(ideal?: true)) | |
expect(Faye::Client).to receive(:new).with(ENV["FAYE_URL"]).and_return(faye) | |
expect(faye).to receive(:publish).with("/sync/generate_csv/#{client.id}", response).and_return(publish) | |
end | |
allow(dbl).to receive(:foo).and_raise("boom") | |
# NOTE нужно установить значение по умолчанию | |
allow(ENV).to receive(:[]).and_call_original | |
allow(ENV).to receive(:[]).with("ENV_TEST").and_return("TEST_VALUE") | |
# rspec | |
.exactly(3).times |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rvm autolibs disable | |
rvm requirements | |
rvm install ruby |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment