Closed10
Half A Loaf Of Ruby
JSON を POST
Faraday ベースに
require 'json'
require 'net/http'
def json_post(url, params)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
headers = { 'Content-Type' => 'application/json' }
http.post(url, params.to_json, headers)
end
url = 'https://example.com'
params = { foo: 'bar' }
response = json_post(url, params)
p response.code
p response.body
Hash の初期化
h, k の rubocop 対応
Hash.new { |h, k| h[k] = [] }
Hash.new { |h, k| h[k] = Hash.new(0) }
Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = [] } }
Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = Hash.new(0) } }
rubocop
自動修正
$ rubocop -a
抑止
全体
.rubocop.yml
AllCops:
NewCops: enable
Style/AsciiComments:
Enabled: false
コード内
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def foo
# 長いコード
end
# rubocop:enable all
# frozen_string_literal: true
CSV
書き出し
CSV.open(filename, 'w') do |csv|
csv << []
end
読み込み
CSV.foreach(filename) do |row|
end
パーセント記法
%q(one two three) #=> "one two three"
%Q(#{1 + 1}) #=> "2"
%w(one two three) #=> ['one', 'two', 'three']
%W(#{1 + 1}) # => [2]
TODO
- minitest
- timecop
- DateTime 廃止 https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c
- Timecop.travel(2000, と直接かける )
- strftime フォーマット
- ruby で Active* 使う方法
Gemfile
# frozen_string_literal: true
source 'https://rubygems.org'
git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
gem 'activerecord'
gem 'activesupport'
gem 'awesome_print'
gem 'faraday'
gem 'msteams-ruby-client'
gem 'mysql2'
gem 'twilio-ruby'
group :development do
gem 'rubocop'
end
group :test do
gem 'minitest'
gem 'minitest-power_assert'
gem 'timecop'
gem 'vcr'
end
ファイルを一気に読む
file = File.open(filename).read
ActiveRecord の結果をハッシュに入れる
Item.all.index_by(&:id)
このスクラップは2021/05/02にクローズされました