ruby apakah suatu string sebenarnya angka?
validate.rb
# source: https://stackoverflow.com/posts/1235990/revisions
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
def is_integer?(str)
!!Integer(str, 10)
rescue ArgumentError, TypeError
false
end
def is_float?(str)
!!Float(str)
rescue ArgumentError, TypeError
false
end
ruby 制作Multilab
setMulilab.rb
Lab.find_by_title("File Inclusion Vulnerabilities").update(requirements: ["requirement"], outcomes: ["outcome"], format: "multi")
ruby 实验室同步
rails-commands
Machine::Cluster.last.sync!
ruby 轨のバリデーション用正规表现集
轨のバリデーション用正规表现集
rails-validates.rb
#
# 数字
#
# 全て数値(全角)
/^[0-9]+$/
# 全て数値(半角)
/^[0-9]+$/
# 全て数値(全角,半角)
/^[0-90-9]+$/
# 全て全角数値(マイナス、小数点)
/^[ー]?[0-9]+(\.[0-9]+)?$/
# 全て半角数値(マイナス、小数点)
/^[-]?[0-9]+(\.[0-9]+)?$/
#
# 文字
#
# 半角アルファベット(小文字)
/^[a-z]+$/
# 半角アルファベット(大文字)
/^[A-Z]+$/
# 半角アルファベット(大文字・小文字)
/^[a-zA-Z]+$/
# 半角アルファベット(小文字・数値)
/^[a-z0-9]+$/
# 半角アルファベット(大文字・数値)
/^[A-Z0-9]+$/
# 半角アルファベット(大文字・小文字・数値)
/^[a-zA-Z0-9]+$/
# 全角ひらがな
/^[ぁ-んー-]+$/
# 全角カタカナ
/^[ァ-ンー-]+$/
# 全角ひらがな、カタカナ
/^[ぁ-んァ-ンー-]+$/
# 半角カナ
/^[ァ-ン゙゚]+$/
# 漢字
/^[一-龥]+$/
# 全角ひらがな、漢字
/^[一-龥ぁ-ん]/
# 全角ひらがな、全角カタカナ、漢字
/^[ぁ-んァ-ン一-龥]/
# 全角ひらがな、全角カタカナ、漢字(鬼車)
/\A(?:\p{Hiragana}|\p{Katakana}|[ー-]|[一-龠々])+\z/
#
# 郵便番号
#
# 郵便番号(ハイフンあり3桁・5桁・7桁)
/^\d{3}[-]\d{4}$|^\d{3}[-]\d{2}$|^\d{3}$/
# 郵便番号(ハイフンあり5桁)
/^\d{3}[-]\d{2}$/
# 郵便番号(ハイフンあり7桁)
/^\d{3}[-]\d{4}$/
# 郵便番号(ハイフンなし3桁)
/^\d{3}$/
# 郵便番号(ハイフンなし5桁)
/^\d{5}$/
# 郵便番号(ハイフンなし7桁)
/^\d{7}$/
# 郵便番号(ハイフンあり・なし両方)
/^\d{3}[-]\d{4}$|^\d{3}[-]\d{2}$|^\d{3}$|^\d{5}$|^\d{7}$/
#
# 電話番号
#
# 電話番号(ハイフンなし10桁)
/^\d{10}$/
# 携帯番号(ハイフンなし11桁)
/^\d{11}$/
# 携帯番号(ハイフンなし10桁or11桁)
/^\d{10}$|^\d{11}$/
#
# その他
#
# e-mail
/^\S+@\S+\.\S+$/
# URL
/^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/
# クレジットカード(VISA,Master,Diners,Discover,Amex対応)
/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/
ruby 虚拟属性案例示例
虚拟属性案例示例
virtual-attributes_example_test.rb
# frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem 'activerecord'
gem 'sqlite3', '~> 1.3.6'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :author_first_name
t.string :author_last_name
t.text :metadata
end
end
class Post < ActiveRecord::Base
# Virtual attributes with Ruby methods
attr_accessor :simple_virtual_attribute_without_type_cast
attr_reader :simple_virtual_attribute_with_type_cast
def simple_virtual_attribute_with_type_cast=(value)
@simple_virtual_attribute_with_type_cast = value.to_i
end
# Extends with Rails API to have more advanced features like type casting and dirty handling
attribute :virtual_attribute_with_type_cast, :boolean
# Use case of virtual attr: to on/off hooks
before_validation if: :virtual_attribute_with_type_cast do
self.simple_virtual_attribute_without_type_cast = 'Virtual attr has been set to true'
end
# Use case of virtual attr: decorator to store composite values
# Simple virtual attribute with pre-processing values and store in persistent attributes
def author_full_name
[author_first_name, author_last_name].join(' ')
end
def author_full_name=(name)
split = name.split(' ', 2)
self.author_first_name = split.first
self.author_last_name = split.last
end
# Custom type casting without introducing & registering new type in Rails
attribute :metadata_raw_json
serialize :metadata, Hash
validate :metadata_raw_json_valid_format, if: -> { @metadata_raw_json.present? }
def metadata_raw_json
@metadata_raw_json || metadata.to_json
end
def metadata_raw_json=(value)
@metadata_raw_json = value
self.metadata = build_metadata_from(@metadata_raw_json)
end
private
def build_metadata_from(json)
try_parse_metadata!(json)
rescue JSON::ParserError
nil
end
def metadata_raw_json_valid_format
errors.add(:metadata_raw_json, 'invalid JSON format') unless json?(@metadata_raw_json)
end
def json?(raw_json)
try_parse_metadata!(raw_json).present?
rescue JSON::ParserError
false
end
# @raise JSON::ParserError
def try_parse_metadata!(value)
ActiveSupport::JSON.decode(value)
end
end
class VirtualAttributesUseCase < Minitest::Test
def test_simple_virtual_attribute
assert_equal(
'1',
Post.new(simple_virtual_attribute_without_type_cast: '1')
.simple_virtual_attribute_without_type_cast
)
assert_equal(
1,
Post.new(simple_virtual_attribute_without_type_cast: 1)
.simple_virtual_attribute_without_type_cast
)
# No dirty enabled
refute Post.new.respond_to?(:simple_virtual_attribute_without_type_cast_changed?)
assert_equal(
1,
Post.new(simple_virtual_attribute_with_type_cast: '1')
.simple_virtual_attribute_with_type_cast
)
assert_equal(
1,
Post.new(simple_virtual_attribute_with_type_cast: 1)
.simple_virtual_attribute_with_type_cast
)
end
def test_simple_virtual_attribute_with_custom_typecast
assert_equal(
1,
Post.new(simple_virtual_attribute_with_type_cast: '1')
.simple_virtual_attribute_with_type_cast
)
assert_equal(
1,
Post.new(simple_virtual_attribute_with_type_cast: 1)
.simple_virtual_attribute_with_type_cast
)
end
def test_attribute_api
post = Post.new virtual_attribute_with_type_cast: '1'
assert_equal true, post.virtual_attribute_with_type_cast, 'type casting works'
assert post.virtual_attribute_with_type_cast_changed?, 'dirty module has been enabled'
end
# Most common usage of virtual attributes to pre-process new values before save
def test_virtual_attribute_with_custom_processing
post = Post.create! author_full_name: 'Paul Keen'
assert_equal 'Paul', post.author_first_name
assert_equal 'Keen', post.author_last_name
post = Post.create! author_first_name: 'Paul', author_last_name: 'Keen'
assert_equal 'Paul Keen', post.author_full_name
end
# Common usage of virtual attributes to enable/disable hooks
def test_virtual_attribute_in_hooks
post = Post.new virtual_attribute_with_type_cast: '1'
post.valid?
assert_equal 'Virtual attr has been set to true', post.simple_virtual_attribute_without_type_cast
end
# Some type casting operations could throw runtime errors or require some schema.
# For this we need more advance cases
def test_virtual_attributes_with_validation_input_before_cast
post = Post.new metadata_raw_json: 'invalid JSON document'
refute post.valid?
post = Post.create! metadata: { existed: 'json' }
post.update metadata_raw_json: 'invalid JSON document'
refute post.valid?
assert_equal({}, post.metadata)
assert post.errors[:metadata_raw_json].present?
post = Post.create! metadata: { existed: 'json' }
post.update metadata_raw_json: '{ "valid": "json" }'
assert post.valid?
assert 'json', post.metadata['valid']
post = Post.new metadata_raw_json: '{ "valid": "json" }'
assert 'json', post.metadata['valid']
post = Post.new metadata_raw_json: '{ "valid": "json" }', metadata: { invalid: 'false' }
assert 'json', post.metadata['valid']
post = Post.new metadata: { invalid: 'false' }, metadata_raw_json: '{ "valid": "json" }'
assert 'json', post.metadata['valid']
post = Post.new metadata: { invalid: 'false' }
assert_equal '{"invalid":"false"}', post.metadata_raw_json
end
end
ruby 日期到时间
日期到时间
dates_to_time.rb
def dates_to_time(date_string, created_at)
if date_string[/[0-9]+/].blank?
# there aren't any numbers in it
return 0
else
# there's at least one number to derive date from
if date_string[/\'(\d){2}/].present?
# uses Month '14 for example
matched_year = date_string[/\'(\d){2}/]
# extrapolate the decade from when this record was created
decade = created_at.blank? ? "20" : created_at.strftime("%Y")[0..1]
return Chronic.parse(date_string.gsub("'", decade)).at_beginning_of_month.to_time.to_i
elsif date_string[/or|\-/].present?
# uses 'date - date' OR 'date or date' or 'date-date'
splitter = date_string[/or|\-/]
return Chronic.parse(date_string.split(splitter).first.strip).to_time.to_i
else
return 0
end
end
end
ruby 方便的片段
rules.rb
class SomeRuleSet
def self.criteria
constraints.map(&:description)
end
def self.constraints
[
Constraints::Max.new('something', 12, 'days', &:value),
Constraints::Max.new('another', 42, 'months', &:value),
Constraints::Match.new('example', nil, &:value),
Constraints::Range.new('range example', 5, 10, &:value)
]
end
def self.run(some_object_array)
some_object_array
.map { |thing| Result.new(thing) }
.each { |result| result.apply_constraints(constraints) }
end
end
# result object
class Result
attr_reader :thing
def initialize(thing)
@thing = thing
@passed = true
@fail_reasons = []
end
def apply_constraints(constraints)
constraints.each do |constraint|
result = constraint.evaluate(thing)
@passed &&= result.passed
@fail_reasons << result.detail unless result.passed
end
end
def fail_reasons
@fail_reasons.join(' ')
end
def passed?
@passed
end
end
# contraint result
module Constraints
class Result
attr_reader :passed, :skipped, :detail
def initialize(passed, detail, skipped = false)
@passed = passed
@skipped = skipped
@detail = detail
end
end
end
# example constraints
module Constraints
class Max
def initialize(item_name, amount, unit, &block)
@amount = amount
@item_name = item_name
@block = block
@unit = unit
end
def description
"Max #{@item_name} of #{@amount} #{@unit}"
end
def evaluate(thing)
val = @block.call(thing)
if val.nil?
Result.new(false, "There is no value for #{@item_name}.")
elsif val <= @amount
Result.new(true, "#{@item_name} is less than #{@amount} #{@unit}.")
else
Result.new(false, "max range reached for #{@item_name}.")
end
end
end
end
ruby SVGファイルを苹果机のアイコン形式ICNS(视网膜対応)に変换するだけ
SVGファイルを苹果机のアイコン形式ICNS(视网膜対応)に変换するだけ
svg2icns.rb
#!/usr/bin/env ruby
# svg2icns.rb
# Copyright (c) 2015 IGARASHI Makoto (raccy)
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
# SVGファイルをMacのアイコン形式であるicnsに変換します。
# 作成されるicnsはRetina対応です。
# SVGファイルはあらかじめ正方形にしておいて下さい。
# そうじゃないと歪みます。
# 実行前に、"gem install rsvg2" しておいてください。
# 既存ファイルは問答無用で上書きされますので注意して下さい。
require "rsvg2"
PNG_ICONSET = {
16 => ["icon_16x16.png"],
32 => ["icon_16x16@2x.png", "icon_32x32.png"],
64 => ["icon_32x32@2x.png"],
128 => ["icon_128x128.png"],
256 => ["icon_128x128@2x.png", "icon_256x256.png"],
512 => ["icon_256x256@2x.png", "icon_512x512.png"],
1024 => ["icon_512x512@2x.png"],
}
def svg2iconset(svg_file, iconset_dir)
rsvg = RSVG::Handle.new_from_data(IO.read(svg_file))
PNG_ICONSET.each_pair do |size, png_list|
png_list.each do |png_file|
surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, size, size)
context = Cairo::Context.new(surface)
context.scale(size.to_f / rsvg.width, size.to_f / rsvg.height)
context.render_rsvg_handle(rsvg)
File.open(File.join(iconset_dir, png_file), "wb") do |io|
surface.write_to_png(io)
end
end
end
end
def iconset2icns(iconset_dir)
system("iconutil -c icns '#{iconset_dir}'")
end
if $0 == __FILE__
if ARGV.size < 1
puts "svg2icns.rb - SVGファイルをICNSに変換するツール"
puts "使い方: ruby #{$0} svg_file"
exit 1
end
svg_file = ARGV[0]
svg_file_ext = File.extname(svg_file)
iconset_dir = File.join(File.dirname(svg_file),
File.basename(svg_file, svg_file_ext) + ".iconset")
unless svg_file_ext.downcase == ".svg"
warn "指定したファイルがSVGではないようです。"
exit 2
end
unless FileTest.file?(svg_file)
warn "ファイルが見つかりません。"
exit 2
end
unless FileTest.directory?(iconset_dir)
Dir.mkdir(iconset_dir)
end
svg2iconset(svg_file, iconset_dir)
iconset2icns(iconset_dir)
end
ruby 雾试验
雾试验
fog-test.rb
#!/usr/bin/env ruby
require 'fog'
client = ::Fog::Compute.new(
:provider => 'vsphere',
:vsphere_username => '',
:vsphere_password => '',
:vsphere_server => '',
:vsphere_expected_pubkey_hash => '',
)
interface_attrs = {
network: 'LX-LAN-VLAN-775',
type: 'VirtualE1000'
}
attrs = {
:name => 'some.example.com',
:memory_mb => '768',
:interfaces => [ interface_attrs ],
:volumes => [
{
:storage_pod => 'Some-Mirror-Pod',
:name => 'Hard disk',
:size_gb => '10',
:thin => 'true',
:eager_zero => 'false'
}
],
:scsi_controller=> {
:type=>"VirtualLsiLogicController"
},
:datacenter => "Toledo",
:boot_order => ["network", "disk"],
:cpus => "1",
:corespersocket => "1",
:cluster=>"Some-Cluster",
:resource_pool=>"default",
:path => "/Datencenter/Some/path",
:guest_id=>"rhel7_64Guest",
:memoryHotAddEnabled=>"1",
:cpuHotAddEnabled=>"1",
:start=>"1",
:annotation=>"test vm"
}
vm = client.servers.new(attrs)
vm.save
ruby 非阻塞的例子
非阻塞的例子
examples_of_implementations.rb
require 'async/http/faraday'
require 'async/http/response'
require 'async/http/server'
require 'async/http/url_endpoint'
require 'async/reactor'
require 'uri/http'
# Make it the global default:
Faraday.default_adapter = :async_http
require 'async'
require 'async/http/internet'
TEST_LINKS = %w[http://google.com http://youtube.com http://facebook.com http://baidu.com http://wikipedia.org http://qq.com http://yahoo.com http://taobao.com http://twitter.com http://amazon.com http://vk.com http://sohu.com http://tmall.com http://instagram.com http://live.com http://jd.com http://weibo.com http://reddit.com http://blogspot.com http://linkedin.com http://netflix.com http://livejasmin.com http://porn555.com http://twitch.tv http://360.cn http://yahoo.co.jp http://pornhub.com http://csdn.net http://instructure.com http://xnxx.com http://xinhuanet.com http://bbc.com http://youku.com http://ettoday.net http://roblox.com http://1688.com http://nytimes.com http://google.es http://booking.com http://quora.com http://onlinesbi.com http://spotify.com http://ifeng.com http://soundcloud.com http://bbc.co.uk http://stackexchange.com http://aliyun.com http://bongacams.com http://popads.net http://nih.gov http://google.com.mx http://chase.com http://45eijvhgj2.com http://49oa3o49b6.com http://vimeo.com http://ebay.de http://researchgate.net http://soso.com http://craigslist.org http://eastday.com http://daum.net http://openload.co http://indiatimes.com http://bukalapak.com http://espn.com http://discordapp.com http://dailymotion.com http://google.com.tr http://txxx.com http://theguardian.com http://dolohen.com http://indeed.com http://google.com.tw http://hupu.com http://mediafire.com http://w3schools.com http://globo.com http://fc2.com http://ebay.co.uk http://youdao.com http://mercadolivre.com.br http://so.com http://mozilla.org http://uol.com.br http://steamcommunity.com http://trello.com http://vice.com http://wetransfer.com http://google.ca http://panda.tv http://godaddy.com http://bet9ja.com http://etsy.com http://yts.am http://slack.com http://slideshare.net http://smzdm.com http://atabencot.net http://softonic.com http://alibaba.com http://babytree.com http://cobalten.com http://spankbang.com http://flipkart.com http://zoom.us http://shutterstock.com http://duckduckgo.com http://amazon.it http://chaturbate.com http://zhanqi.tv http://canva.com http://intuit.com http://tokopedia.com http://toutiao.com http://blogger.com http://weather.com http://bankofamerica.com http://yelp.com http://otvfoco.com.br http://kakaku.com http://foxnews.com http://sciencedirect.com http://deviantart.com http://amazon.fr http://zillow.com http://3dmgame.com http://google.pl http://ea.com http://mega.nz http://youm7.com http://steampowered.com http://myshopify.com http://freepik.com http://cnet.com http://google.com.eg http://amazon.cn http://twimg.com http://savefrom.net http://messenger.com http://walmart.com http://kompas.com http://google.com.ar http://digikala.com http://dailymail.co.uk http://onlinevideoconverter.com http://google.com.sa http://huanqiu.com http://wellsfargo.com http://medium.com http://patria.org.ve http://google.co.th http://hantinlethemsed.info http://abs-cbn.com http://google.co.id http://ladbible.com http://google.co.kr http://youporn.com http://hulu.com http://speedtest.net http://gamersky.com http://tantiterhalac.info http://wikihow.com http://quizlet.com http://scribd.com http://shopify.com http://epicgames.com http://udemy.com http://livejournal.com http://doublepimp.com http://google.com.au http://primevideo.com http://liputan6.com http://breitbart.com http://varzesh3.com http://amazon.es http://ebay-kleinanzeigen.de http://sindonews.com http://thepiratebay.org http://doubleclick.net http://line.me http://gearbest.com http://bodelen.com http://archive.org http://egy.best http://1337x.to http://news-speaker.com http://genius.com http://gamepedia.com http://pinimg.com http://gfycat.com http://zendesk.com http://rutracker.org http://zoho.com http://tripadvisor.com http://9gag.com http://allegro.pl http://amazon.ca http://youth.cn http://okta.com http://livedoor.com http://office365.com http://wikimedia.org http://sarkariresult.com http://mailchimp.com http://redd.it http://myway.com http://forbes.com http://cloudfront.net http://momoshop.com.tw http://ndtv.com http://cnki.net http://usps.com http://washingtonpost.com http://reverso.net http://tistory.com http://weebly.com http://namnak.com http://dmm.co.jp http://58.com http://behance.net http://rt.com http://ameblo.jp http://taboola.com http://ikea.com http://chinaz.com http://list.tmall.com http://wordpress.org http://cdninstagram.com http://tencent.com http://pixiv.net http://box.com http://ltn.com.tw http://buzzfeed.com http://hp.com http://ctrip.com http://uptodown.com http://thesaurus.com http://rephartertonelin.info http://google.com.ua http://v2ex.com http://crunchyroll.com http://fiverr.com http://airbnb.com http://redtube.com http://ouo.io http://hotstar.com http://blackboard.com http://academia.edu http://xfinity.com http://getawesome1.com http://livedoor.jp http://zippyshare.com http://pixabay.com http://ask.com http://segmentfault.com http://capitalone.com http://orange.fr http://googlevideo.com http://k618.cn http://nga.cn http://wordreference.com http://atlassian.net http://oracle.com http://bestbuy.com http://yy.com http://mercadolibre.com.ar http://patreon.com http://gamespot.com http://sex.com http://okdiario.com http://exoclick.com http://bp.blogspot.com http://americanexpress.com http://samsung.com http://hola.com http://dytt8.net http://wix.com http://aol.com http://360doc.com http://2345.com http://cambridge.org http://hclips.com http://skype.com http://evernote.com http://ign.com http://siteadvisor.com http://rarbg.to http://namu.wiki http://dell.com http://google.gr http://baike.com http://op.gg http://dianping.com http://bitly.com http://rednet.cn http://sourceforge.net http://hdfcbank.com http://ups.com http://wease.im http://hotnewhiphop.com http://grid.id http://fedex.com http://52pojie.cn http://setn.com http://droom.in http://grammarly.com http://dkn.tv http://friv.com http://ali213.net http://irctc.co.in http://flickr.com http://kaskus.co.id http://indoxxi.bz http://browsergames2018.com http://pulzo.com http://userapi.com http://olx.ua http://sci-hub.tw http://nownews.com http://elmundo.es http://58pic.com http://asana.com http://ieee.org http://flvto.biz http://rarbgprx.org http://japanpost.jp http://ithome.com http://canalrcn.com http://asahi.com http://americanas.com.br http://kapanlagi.com http://torrentz2.eu http://google.co.ao http://google.nl http://visualstudio.com http://playjunkie.com http://bitbucket.org http://viva.co.id http://suning.com http://tomshardware.com http://pconline.com.cn http://rbc.ru http://vnexpress.net http://yespornplease.com http://hotmovs.com http://paytm.com http://fb.ru http://newstrend.news http://thispersondoesnotexist.com http://yandex.com.tr http://gmanetwork.com http://spotscenered.info http://archiveofourown.org http://zimuzu.io http://techradar.com http://arxiv.org http://docin.com http://thehill.com http://lordfilms.tv http://uptobox.com http://n11.com http://codepen.io http://drudgereport.com http://wondershare.com http://mileroticos.com http://myanmarload.com http://android.com http://duolingo.com http://hdlava.me http://gmarket.co.kr http://internetdownloadmanager.com http://gyazo.com http://udn.com http://impress.co.jp http://nintendo.com http://dribbble.com http://doorblog.jp http://hotels.com http://dafont.com http://milliyet.com.tr http://hepsiburada.com http://elwatannews.com http://investopedia.com http://kaoyan.com http://filehippo.com http://interia.pl http://justdial.com http://utorrent.com http://yaplakal.com http://coursera.org http://hdzog.com http://google.sk http://liepin.com http://rotumal.com http://envato.com http://namasha.com http://nutaku.net http://livescore.com http://blog.me http://lifo.gr http://nvidia.com http://groupon.com http://elmogaz.com http://t-online.de http://4399.com http://xda-developers.com http://cima4u.tv http://huffingtonpost.com http://marial.pro http://firefoxchina.cn http://marriott.com http://google.at http://google.se http://hh.ru http://avast.com http://hamariweb.com http://33sk.tv http://hatena.ne.jp http://cnnindonesia.com http://bicentenariobu.com http://cloudflare.com http://tarafdari.com http://creditkarma.com http://teamviewer.com http://film2movie.ws http://uzone.id http://state.gov http://tube8.com http://wowhead.com http://chip.de http://bhphotovideo.com http://reclameaqui.com.br http://flaticon.com http://news18.com http://dcard.tw http://yandex.com http://google.com.ph http://indiamart.com http://xiaohongshu.com http://socialblade.com http://vanguardngr.com http://ticketmaster.com http://issuu.com http://3c.tmall.com http://getpocket.com http://caixa.gov.br http://clien.net http://realtor.com http://keyrolan.com http://cdiscount.com http://yandex.by http://canada.ca http://eztv.io http://book118.com http://python.org http://kijiji.ca http://zing.vn http://newsmth.net http://kakao.com http://naver.jp http://mercadolibre.com.ve http://torrentwal.com http://weather.com.cn http://southwest.com http://auction.co.kr http://lianjia.com http://qualtrics.com http://gotporn.com http://brilio.net http://timeanddate.com http://ruliweb.com http://wargaming.net http://telegraph.co.uk http://vidio.com http://dailycaller.com http://hltv.org http://hm.com http://shopee.tw http://costco.com http://lolesports.com http://vesti.ru http://google.hu http://superuser.com http://subito.it http://mtime.com http://ebay.fr http://dawn.com http://pngtree.com http://weibo.cn http://thingiverse.com http://lefigaro.fr http://imooc.com http://battle.net http://ivi.ru http://unblocked.cx http://gome.com.cn http://turbobit.net http://ninisite.com http://tabelog.com http://polygon.com http://ozon.ru http://sonyliv.com http://qidian.com http://www.gov.uk http://amazon.com.mx http://guancha.cn http://usaa.com http://google.ae http://nnu.ng http://uploaded.net http://indianexpress.com http://11st.co.kr http://coursehero.com http://futbin.com http://mydiba.xyz http://xueqiu.com http://inven.co.kr http://blibli.com http://stanford.edu http://xiaomi.com http://royalbank.com http://verizonwireless.com http://pirateproxy.bet http://4pda.ru http://corriere.it http://6.cn http://yenisafak.com http://zougla.gr http://redfin.com http://uigruwtql.com http://provincial.com http://shimo.im http://tamilrockerss.ch http://indiatoday.in http://ytimg.com http://lifewire.com http://macys.com http://goal.com http://marketwatch.com http://harvard.edu http://wildberries.ru http://huffpost.com http://nasa.gov http://addroplet.com http://pku.edu.cn http://mathworks.com http://infobae.com http://tsinghua.edu.cn http://biblegateway.com http://upornia.com http://familydoctor.com.cn http://ssc.nic.in http://znanija.com http://vmall.com http://mobile.de http://getlnk2.com http://eporner.com http://17track.net http://wikiwand.com http://shein.com http://nordstrom.com http://secureserver.net http://narcity.com http://atlassian.com http://labanquepostale.fr http://ruten.com.tw http://depositphotos.com http://bookmyshow.com http://express.co.uk http://lemonde.fr http://prom.ua http://adme.ru http://vy4e3jw46l.com http://2ch.net http://apache.org http://kayak.com http://storm.mg http://nypost.com http://ubisoft.com http://a9vg.com http://delta.com http://britannica.com http://addthis.com http://cqnews.net http://donga.com http://rutube.ru http://msi.com http://pornpics.com http://andhrajyothy.com http://service-now.com http://href.li http://tandfonline.com http://dnevnik.ru http://norton.com http://kinozal.tv http://189.cn http://google.cz http://xhamsterlive.com http://media.tumblr.com http://tamasha.com http://2movierulz.gs http://abola.pt http://perfectgirls.net http://hootsuite.com http://yifysubtitles.com http://qichacha.com http://4chan.org http://ebates.com http://sportbible.com http://myfreecams.com http://el-nacional.com http://jooble.org http://study.com http://4shared.com http://12306.cn http://ancestry.com].shuffle!.freeze
def faraday_example
Async::Reactor.run do |task|
TEST_LINKS[0..100].each do |link|
task.async do |subtask|
response = Faraday.get link
response.status
end
end
end
end
def async_process_http
Async::Reactor.run do |task|
TEST_LINKS[100..200].each do |link|
task.async do |subtask|
uri = Async::HTTP::URLEndpoint.parse(link)
client = Async::HTTP::Client.new(uri)
response = client.get('/')
response.status
end
end
end
end
require 'concurrent'
def concurrent_ruby_example
pool = Concurrent::FixedThreadPool.new(100) # 5 threads
TEST_LINKS[200..300].each do |link|
pool.post do
uri = Async::HTTP::URLEndpoint.parse(link)
client = Async::HTTP::Client.new(uri)
response = client.get('/')
response.status
end
end
end
require 'benchmark/ips'
Benchmark.ips do |benchmark|
# benchmark.time = 10
benchmark.warmup = 0
benchmark.report('faraday') do |count|
faraday_example
end
benchmark.report('async_http') do |count|
async_process_http
end
benchmark.report('thread_pool') do |count|
concurrent_ruby_example
end
benchmark.compare!
end