Closed10

Half A Loaf Of Ruby

oooooooooooooooo

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
oooooooooooooooo

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) } }
oooooooooooooooo

CSV

書き出し

CSV.open(filename, 'w') do |csv|
  csv << []
end

読み込み

CSV.foreach(filename) do |row|
end
oooooooooooooooo

パーセント記法

%q(one two three) #=> "one two three"
%Q(#{1 + 1}) #=> "2"

%w(one two three) #=> ['one', 'two', 'three']
%W(#{1 + 1}) # => [2]
oooooooooooooooo

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
oooooooooooooooo

ActiveRecord の結果をハッシュに入れる

Item.all.index_by(&:id)
このスクラップは2021/05/02にクローズされました