(Linux|HomeBrew|Ruby)HomeBrewとRubyのインストール関連

ゴール:

やること:

  • HomeBrew(LinuxBrew)をインストール

  • rbenvインストール

  • rbenvでRubyのバージョンを管理する

環境:

  • Windows10上のWSL2(Ubuntu 18.04.6 LTS)

Rubyのインストール

$ sudo apt install ruby

HomeBrewのインストール

確認:

  • Installation successful
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

<<略>>

==> Installation successful!

==> Homebrew has enabled anonymous aggregate formulae and cask analytics.
Read the analytics documentation (and how to opt-out) here:
  https://docs.brew.sh/Analytics
No analytics data has been sent yet (nor will any be during this install run).

==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
  https://github.com/Homebrew/brew#donations

==> Next steps:
- Run these two commands in your terminal to add Homebrew to your PATH:
    echo 'eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"' >> /home/masawa/.profile
    eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
- Install Homebrew's dependencies if you have sudo access:
    sudo apt-get install build-essential
  For more information, see:
    https://docs.brew.sh/Homebrew-on-Linux
- We recommend that you install GCC:
    brew install gcc
- Run brew help to get started
- Further documentation:
    https://docs.brew.sh

環境変数追加

$ echo 'eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"' >> /home/masawa/.profile
$ eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"

rbenvインストール

$ brew install rbenv

rbenvでRubyのバージョンを管理する

確認:

  • BUILD FAILED

  • error: no acceptable C compiler とログ出力されている。

参照:
ChromebookにHomebrew(Linuxbrew)をインストールする

$ rbenv install 3.1.2
Downloading ruby-3.1.2.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.1/ruby-3.1.2.tar.gz
Installing ruby-3.1.2...
ruby-build: using readline from homebrew

BUILD FAILED (Ubuntu 18.04 using ruby-build 20220426)

Inspect or clean up the working tree at /tmp/ruby-build.20220603094749.27208.cWN6BQ
Results logged to /tmp/ruby-build.20220603094749.27208.log

Last 10 log lines:
checking target system type... x86_64-pc-linux-gnu
checking for gcc... no
checking for clang... no
checking for cc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/tmp/ruby-build.20220603094749.27208.cWN6BQ/ruby-3.1.2':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details

Cコンパイラをインストール

$ sudo apt-get install build-essential curl file git

改めてrbenvでRubyのバージョンを管理する

確認:

  • BUILD FAILED

  • Try running apt-get install -y zlib1g-dev to fetch missing dependencies.

$ rbenv install 3.1.2
Downloading ruby-3.1.2.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.1/ruby-3.1.2.tar.gz
Installing ruby-3.1.2...
ruby-build: using readline from homebrew

BUILD FAILED (Ubuntu 18.04 using ruby-build 20220426)

Inspect or clean up the working tree at /tmp/ruby-build.20220603095259.32560.dtG6mA
Results logged to /tmp/ruby-build.20220603095259.32560.log

Last 10 log lines:
The Ruby zlib extension was not compiled.
ERROR: Ruby install aborted due to missing extensions
Try running `apt-get install -y zlib1g-dev` to fetch missing dependencies.

Configure options used:
  --prefix=/home/masawa/.rbenv/versions/3.1.2
  --enable-shared
  --with-readline-dir=/home/linuxbrew/.linuxbrew/opt/readline
  LDFLAGS=-L/home/masawa/.rbenv/versions/3.1.2/lib
  CPPFLAGS=-I/home/masawa/.rbenv/versions/3.1.2/include

zlib1g-devをインストール

$ sudo apt-get install -y zlib1g-dev

改めてrbenvでRubyのバージョンを管理する

$ rbenv install 3.1.2
Downloading ruby-3.1.2.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.1/ruby-3.1.2.tar.gz
Installing ruby-3.1.2...
ruby-build: using readline from homebrew

確認

$ rbenv versions
* system
  3.1.2
$ rbenv global 3.1.2
$ rbenv versions
  system
* 3.1.2 (set by /home/masawa/.rbenv/version)

OK!

(Java, SpringBoot)出会ったアノテーションまとめ

SpringBootを使ってきて出会ったアノテーションを羅列。
分類は適当。


アノテーション 付与先 メモ
@Controller このクラスがコントローラであることを示す @Controlelr
public class HelloController {}
@RequestMapping HTTPリクエストを受け付ける。http://localhost:8080/hello @RequestMapping("/hello")
public String hello() { return "Hello"; }
@GetMapping HTTPのGETメソッドを受け付ける @GetMapping("/hello")
public String hello() { return "Hello"; }
@PostMapping HTTPのPOSTメソッドを受け付ける @PostMapping("/confirm")
public String confirm() { return "Confirm"; }
@RequestParam リクエストの値を取得する public String greet(@RequestParam("message") String message, Model model)
@Service このクラスがビジネスロジックであることを示す @Service
public class UserDataService {}
@Repository リポジトリであることを示す @Repository
public interface CommentRepository {}
@Data Lombok。GetterやSetterなどの定型コードを自動生成する @Data
public class User {}
@Getter Lombok。Getterの定型コードを自動生成する @Getter
public class User {}
@Setter Lombok。Setterの定型コードを自動生成する @Setter
public class User {}
@ModelAttribute フォーム情報を受け取る(?)。データバインディング @PostMapping
public confirm(@ModelAttribute User user) {}
@Entity エンティティデータであることを示す @Entity
public class Book {}
@Id エンティティの主キー @Id
@GeneratedValue
private Long id;
@GeneratedValue 主キーの値を自動採番する。@Id
@GeneratedValue
private Long id;
@Component このクラスがコンポーネントであることを示す。 @Component
public class DataLoader {}
@Scope Beanのスコープを指定することができる @Scope("singleton")
@Scope("prototype")
@Scope("request")
@Scope("session")
@Scope("websocket")
@Scope("request")は@RequestScope、@Scope("session")は@SessionScope
※指定が無い場合singleton

インジェクション

アノテーション 内容 メモ
@Autowired Springがオブジェクトを管理・インジェクションをしてくれる。 // フィールドインジェクション
@Autowired
private CommentRepository repository;

// コンストラクタインジェクション
private final CommentRepository repository; // finalにできる
public CommentController(CommentRepository repository) { this.repository = repository; }
@RequiredArgsConstructor コンストラクタを自動生成する。Lombokの@RequiredArgsConstructorを使うとコンストラクタ・インジェクションを省略できる

JPA

アノテーション 内容 メモ
@GeneratedValue DBのidentity列を使用してキーを自動採番する。 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne 多対一のテーブルである // departmentテーブルの課が1に対して複数の従業員
public class Employee {
@ManyToOne
private Department department;
}
@OneToMany 一対多のテーブルである public class Department {
@OneToMany(mappedBy = "department")
private List employees;}
@JoinColumn 結合カラムを指定できる public class Employee {
@ManyToOne
@JoinColumn(name = "sample_id")
Department department;
}
@Query JPQL(SQLライク)を用いてテーブル(@Entity)を操作する @Query("SELECT e FROM employees e WHERE e.name LIKE :name")
Collection searchByName(String name);
@Table DBのテーブル名を設定する @Table(name = "employees")
@Entity
public class Employee {}

ロギング

アノテーション 内容 メモ
@Slf4j Lombokのロギングアノテーション @Slf4j
public class StringIocApplication {}

バリデーション(Bean Validation)

アノテーション 内容 メモ
@Validated 入力チェックを行う。BindingResultに検証結果が入る @PostMapping("/confirm")
public String confirm(@Validated @ModelAttribute User user, BindingResult result)
@NumberFormat 指定パターンの文字列を数値に型変換する @NumberFormat(pattern="#,###")
private BigDecimal price;
@DateTimeFormat yyyy-MM-dd形式の文字列を日付に型変換する @DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate date;
@NotBlank 文字列が、nullか空文字、空白(半角)ではないか検証する @NotBlank
String name;
@NotEmpty 文字列がnullか空文字でないか検証する(Collectionもサポート) @NotEmpty
String name;
@NotNull nullでないかを検証する @NotNull
String id;
@Size 文字列の長さが指定の範囲内かを検証する(Collectionもサポート) @Size(min=4, max=100)
String name;
@Email 文字列が有効なメールアドレスかを検証する @Email
String email
@Min 指定の値以上かを検証する。 @Min(1)
Integer age;
@Max 指定の値以下かを検証する。 @Max(120)
Integer age;
@Pattern 文字列が正規表現と一致するかを検証する @Pattern(regexp="[0-9]+")
String phoneNumber;
@AssertFalse Falseであるか検証する @AssertFalse
Boolean isActive;
@AssertTrue Trueであるか検証する @AssertTrue
Boolean isActive;
@Future 日付が未来かどうかを検証する @Future
Date eventDate;
@Past 日付が過去かどうかを検証する @Past
Date eventDate;
@Range 数値が指定の範囲内か検証する @Range(min=1, max=120)
Integer age;
@URL 文字列が有効なURLか検証する @URL
String url;
@CreditCardNumber 文字列が有効なクレジットカード番号であるかを検証する @CreditCardNumber
String cardNumber;
@ISBN 文字列がISBNであるか検証する @ISBN
String isbn;
@Length 文字列のが長さが指定の範囲内か検証する。@Sizeを使用するのを推奨。 @Length(min=4, max=100)
String name;

SpringBootでAPIサーバ

JSONを受け取ってそのままJSONを返却するAPIサーバサンプル

github.com

SpringBootを起動して、先日学んだcurlで、

>curl localhost:8080/authors/get -X GET -H "Content-type: application/json" -d "[{\"name\": \"masawa\", \"age\": 100}]"
[{"name":"masawa","age":100}]

curl

curl

コマンドのオプションが多くて見るのが怖かったcurl
API開発にピッタリのコマンドだったんだ、
もっと早く調べればよかった。。。

いつものように、自分用メモ。

第一歩

Windowsなのでインストール。 (curl - Releases and Downloads)https://curl.haxx.se/download.html
インストールが終わったら実行実行!

サイトにアクセス。

curl http://httpbin.org/get

HTMLが返ってきます。

http://httpbin.org/ さんがcurlの勉強に最適のようです。

HTTPメソッド

GETとかPOSTとかPUTとかDELETEとか。

-X オプションを使う。
(Xは何かな? eXecute?)

>curl -X GET http://httpbin.org/get
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.55.1",
    "X-Amzn-Trace-Id": "Root=1-617aa663-695eff746736e0823a43b1c1"
  },
  "origin": "131.147.82.157",
  "url": "http://httpbin.org/get"
}

データを送りつけよう

JSONを送ってみる。

-dオプションを使う。 (dはDataのdだ。間違いない。)

>curl http://httpbin.org/post -X POST -d "{\"name\": \"masawa\", \"age\": \"123\"}"
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "{\"name\": \"masawa\", \"age\": \"123\"}": ""
  },
  "headers": {
    "Accept": "*/*",
    "Content-Length": "32",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.55.1",
    "X-Amzn-Trace-Id": "Root=1-617aaaae-0840d3c147c17c6100b21605"
  },
  "json": null,
  "origin": "131.147.82.157",
  "url": "http://httpbin.org/post"
}

JSONはダブルクォートをバックスラッシュでエスケープするしかないのかなあ。

HTTPヘッダ

-Hを使う。 (HeaderのHに間違いない。)

>curl http://httpbin.org/post -X POST -H "Content-type: application/jason" -d "{\"name\": \"masawa\", \"age\": \"123\"}"
{
  "args": {},
  "data": "{\"name\": \"masawa\", \"age\": \"123\"}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Content-Length": "32",
    "Content-Type": "application/jason",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.55.1",
    "X-Amzn-Trace-Id": "Root=1-617aacd5-2d9d32b865dacb63608c1829"
  },
  "json": {
    "age": "123",
    "name": "masawa"
  },
  "origin": "131.147.82.157",
  "url": "http://httpbin.org/post"
}

Cookie

-bを使う。 (なんで b なんだーー!)

>curl http://httpbin.org/post -X POST -b 'name=masawa'
{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Cookie": "'name=masawa'",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.55.1",
    "X-Amzn-Trace-Id": "Root=1-617ab33a-1bd8d9c03f31d2b1052aa151"
  },
  "json": null,
  "origin": "131.147.82.157",
  "url": "http://httpbin.org/post"
}

まとめ

curlのオプションは他にも気が遠くなる位ある。

curl -h

でも、今のところは書いてきたようなオプション使えばAPI開発には十分かと思う。

(Java)関数型インターフェース

Javadocを読む時に関数型インターフェースが出てくるといっつもなんだっけこれ?
という場面に遭遇する。物覚えが悪いのです。
関数型インターフェースが出て何年経つのねん。

JavaにStreamが実装された時に追加されたインターフェース。
とはいえ、いろいろなところで使われるようになっている。
Javaに関数型がどんどん導入されるのは喜ばしいことだと思っています。(詳しくはまた書ければいいな)

Function

引数をひとつとり何らかの値を返す。
もっとも使われるか。

Predicate

引数をひとつとりbooleanを返す。
Streamでfilterで使われることが多いのでは?

Consumer

Consumerは何も返さない。
個人的にはStreamでListに追加していくことが多いかな。

Supplier

引数を受け取らず、何らかの値を返す。


後々このエントリーをアップデートしてサンプルコードを書こう!

(Java)Lombokがインストールできない!?

Lombokのインストールでだいぶはまったのでメモがてら。
(ググっても情報なかったけど、常識なのかな?)

Eclipse
Maven

f:id:project-masawa:20210812225900p:plain pom.xmlに書く。

f:id:project-masawa:20210812225918p:plain maven install

f:id:project-masawa:20210812225934p:plain Build Success

f:id:project-masawa:20210812225956p:plain Lombokがない!?

f:id:project-masawa:20210812230053p:plain プロジェクトを右クリック→プロジェクトのビルド

f:id:project-masawa:20210812230126p:plain Lombokがある!!