GitHub内の検索

GitHub内を検索できるのは知っていたのですが、今までリポジトリを検索する為にしか活用できておりませんでした。。。

先ほど、リポジトリ検索だけでなく、コード検索もしてみたのですが、お手本にしたいコードがたーーーくさん出てきてすごく良かったのでその手順について書いておきます。

 

手順

前提

JobのRSpecでのテストのやり方を調べたいとします。

 

「filename:job_spec.rb」でAll GitHub検索をする

RSpecを使ったJobのテストなら、~~job_spec.rbといったファイル名にするはずなので、

「filename:job_spec.rb」でAll GitHub検索を実行します。

これで、~~job_spec.rb というファイル名のコードがたくさんヒットしてくれます!!

*filename:はファイル名を指定できるオプションのようです。

gyazo.com

 

このままですと、Best match順で結果が並んでいるので、sortオプションをRecentryなりに指定してあげれば、ファイル名が完全一致ではなく部分的に一致しているものも上の方に来てくれます。

 

さらに、ファイルをインポートして処理する系のJobのテストの書き方が見たい時は、

「filename:import_job_spec.rb」で検索すれば良さげなお手本コードがたくさん出てきました!!!

 

 

 

感想その他

GitHubすごいです!!!

rails  job  rspec  書き方」などでググってもあまりお手本コードが見つからなかったのですが、GitHubのAll GitHub検索を使うことで良さそうなお手本がたくさんヒットしてくれました!!

コードを公開してくれている方々に感謝です!!!

自分も見られたらまずいコード以外はpublishにして誰でも見れる状態にしていこうと思います!!

 

 

 

リモートのmasterに間違えてmergeしてしまった時

リモートのmasterに間違えてmergeしてしまい、めちゃくちゃ焦る事態がありました。

別に問題のある内容をmergeしてしまった訳ではないのですが、明後日mergeしましょうと話していた内容だったので焦りました。

 

その時の手順についてまとめておきます。

 

手順

①間違えてmergeしてしまったコミットの右にあるRevertボタンをクリック

②するとmergeした内容を取り消すプルリクが作成できるので作成する

③作成したプルリクをmergeする

 

これで間違えてmergeしてしまった内容が取り消されます!!

ぽちぽちボタンを押すだけでしたので簡単でした。。。!!

 

Revertする前と同じプルリクをもう一度作る際は、RevertしたコミットをRevertすることでプルリクを作ってあげる必要があるみたいです!

firebase initしたらError: HTTP Error: 401が出た

エラー内容

firebase initコマンドを実行し、Hostingを選択してエンターしたら、以下のようなエラーが出ました。。。

Error: HTTP Error: 401, Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

 

firebase loginまでは全く問題なく進んでいたのになぜ??となっておりました。

 

 

解決方法

firebase login に、--reauth --no-localhost というオプションをつけると上手くいくという情報をゲットし、実行しました。

$ firebase login --reauth --no-localhost

 

すると以下のようなページがブラウザで自動で開きます。

gyazo.com

 

この画面に表示されているコードをコピーし、ターミナルの以下の部分に続けてペーストしてあげれば、無事firebase initできるようになります!!

 

? Paste authorization code here:ここに上のコードをペーストする 

 

 

感想その他 

なんで普通にfirebase loginしただけだと上手くいかなかったのかはまだ謎です。

firebaseマスターしていきたい!

 

 

TraceLocationというgemを使ってみた!

ツイッターを見ていたら、カルパスさんがコードリーディング用のgemを作ったという情報をgetしたので、早速試してみました!!1

 

以下はそのリポジトリです!

github.com

 

こちらのスライドで、どういう思いで作ったのか・どう使うのかについて書いてくださっております!!

speakerdeck.com

 

 

使ってみる!

railsを使って作成したブログアプリの中にTraceLocationを入れてみました!

 

①gemfileのなかに、gem 'trace_location' を書いてbundle installします。

 

②コンソールを立ち上げ、env = Rack::MockRequest.env_for('http://localhost:3000/api/stories') を実行します。
~/p/r/blog3 (master|✚2) $ rails c
Running via Spring preloader in process 3478
Loading development environment (Rails 5.2.2)
[1] pry(main)> env = Rack::MockRequest.env_for('http://localhost:3000/api/stories')
=> {"rack.version"=>[1, 3],
"rack.input"=>#<StringIO:0x00007fc82759a258>,
"rack.errors"=>#<StringIO:0x00007fc82759a4d8>,
"rack.multithread"=>true,
"rack.multiprocess"=>true,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"GET",
"SERVER_NAME"=>"localhost",
"SERVER_PORT"=>"3000",
"QUERY_STRING"=>"",
"PATH_INFO"=>"/api/stories",
"rack.url_scheme"=>"http",
"HTTPS"=>"off",
"SCRIPT_NAME"=>"",
"CONTENT_LENGTH"=>"0"}

 

 

②TraceLocation.trace { status, headers, body = Rails.application.call(env) } を実行します。
[2] pry(main)> TraceLocation.trace { status, headers, body = Rails.application.call(env) }
Started GET "/api/stories" for at 2019-05-02 22:23:16 +0900
Cannot render console from ! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
(59.1ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
(5.4ms) SELECT `schema_migrations`.`version` FROM `schema_migrations` ORDER BY `schema_migrations`.`version` ASC

ActionController::RoutingError (No route matches [GET] "/api/stories"):

(pry):2:in `block in __pry__'
(pry):2:in `__pry__'
Created at /Users/hayashiyoshino/projects/rails-projects/blog3/log/trace_location-2019050222051556803399.log
=> true

 

 

/log/trace_location-2019050222051556803399.log ファイルを見にいきます。

すると、以下の画像のように、どのディレクトリに・ファイル名・何行目のメソッドが呼ばれたかが書かれているログがみれます!

gyazo.com

 

 

④ログの情報を元にソースコードを追ってみます。

/Users/hayashiyoshino/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails.rb:39#application

を開いてみると、以下のようなメソッドが呼ばれておりました!

def application
@application ||= (app_class.instance if app_class)
end

 

次のログも同じように、

C /Users/hayashiyoshino/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/engine.rb:522#call

を開いてみると、以下のようなメソッドが呼ばれていることがわかりました!!

def call(env)
req = build_request env
app.call req.env
end

 

そしてcallメソッドの中で呼ばれている build_request メソッドは

C /Users/hayashiyoshino/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/application.rb:591#build_request

にあるようです!!

def build_request(env)
req = super
env["ORIGINAL_FULLPATH"] = req.fullpath
env["ORIGINAL_SCRIPT_NAME"] = req.script_name
req
end

 

 

 

感想その他

Rubymineのジャンプ機能を以ってしても迷子になる&人から解説してもらっても所々抜けてしまう自分にとって、とても有難いgemでした!!

コードを追いかけるべき順番と場所がこのようにこまかーーく出てくれているのは有難いです!!

迷子にならずコードを追えるのは非常に快適です!!

それと、以下のツイートでカルパスさんがおっしゃっていたように、bootsnapのログが沢山出るので、コードリーディングするときはbootsnapを呼ばれないようにするのが良さそうです!

 

コードリーディングやってゆきます!!

 

 

Nuxt.jsを触ってみた

今日は前から気になっていた、Nuxt.jsを触ってみました!!

 

 

Nuxt.jsとは

vue.jsでアプリを作るためのフレームワークです。 

 

手順

①npm install -g vue-cli

vueのコマンドラインツールをインストールします。

~ $ npm install -g vue-cli
npm WARN deprecated coffee-script@1.12.7: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/vue -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/vue-cli/bin/vue
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/vue-init -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/vue-cli/bin/vue-init
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/vue-list -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/vue-cli/bin/vue-list
+ vue-cli@2.9.6
added 239 packages from 206 contributors in 12.975s

 

②vue init nuxt-community/starter-template nuxt_sample

nuxt_sampleというアプリ名でサンプルアプリを生成します。

~ $ vue init nuxt-community/starter-template nuxt_sample

? Project name nuxt_sample
? Project description Nuxt.js project
? Author 林佳志乃 <twinklestaryoshino@gmail.com>

vue-cli · Generated "nuxt_sample".

To get started:

cd nuxt_sample
npm install # Or yarn
npm run dev

 

③yarn

ディレクトリを移動し、yarnコマンドを実行します。

しかし自分はyarnコマンドが使えないと言われてしまったので、yarnのインストールからすることにしました。 

~ $ cd nuxt_sample
~/nuxt_sample $ yarn
fish: Unknown command 'yarn'

 

npm install -g yarnというコマンドでyarnをグローバルにインストールし、パスも通るようにします。

~/nuxt_sample [127] $ npm install -g yarn
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/yarn -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/yarn/bin/yarn.js
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/yarnpkg -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/yarn/bin/yarn.js
+ yarn@1.15.2
added 1 package in 12.275s


╭───────────────────────────────────────────────────────────────╮
│ │
New minor version of npm available! 6.4.1 6.9.0
Changelog: https://github.com/npm/cli/releases/tag/v6.9.0
Run npm install -g npm to update! │
│ │
╰───────────────────────────────────────────────────────────────╯

 

無事インストールされたので、yarnコマンドを実行します。

~/nuxt_sample $ yarn
yarn install v1.15.2
info No lockfile found.
[1/4] 🔍 Resolving packages...
warning eslint > file-entry-cache > flat-cache > circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
warning " > eslint-loader@2.1.2" has unmet peer dependency "webpack@>=2.0.0 <5.0.0".
[4/4] 🔨 Building fresh packages...
success Saved lockfile.
Done in 90.73s. 

 

④yarn dev

yarn devコマンドでnuxtアプリを立ち上げます。

 

  ~/nuxt_sample $ yarn dev
yarn run v1.15.2
$ nuxt

╭─────────────────────────────────────────────╮
│ │
Nuxt.js v2.6.3
Running in development mode (universal) │
│ │
Listening on: http://localhost:3000/ │
│ │
╰─────────────────────────────────────────────╯

Preparing project for development 14:45:47
Initial build may take a while 14:45:47
Builder initialized 14:45:47
Nuxt files generated 14:45:47

Client
Compiled successfully in 7.78s

Server
Compiled successfully in 6.99s

Waiting for file changes 14:45:58
Memory usage: 140 MB (RSS: 160 MB) 14:45:58
^C⏎

 

 

 これで、localhost:3000にアクセスすると、アプリが見れる状態になります!

gyazo.com

 

 

 

この後、TODOアプリなり、チャットアプリなりを作ってデプロイまでしていこうと思います!

 

 

ngコマンドが動く環境構築

某サイトを修正するにあたって、「ng serve」 など、ngコマンドを使う必要があったのですが、環境構築で少し苦戦しました。ngコマンドが何物なのかもよくわかっておりませんでした。

その概要と環境構築の手順を書き留めておきます。

 

ngコマンドとは

Angular CLIで使えるようになるコマンドです。

ng new、ng serve、ng build などがあります。

github.com

 

手順

①npm install -g @angular/cli

npm installでAngularのコマンドラインツールをインストールします。

$ npm install -g @angular/cli
/Users/hayashiyoshino/.nodebrew/node/v11.0.0/bin/ng -> /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/@angular/cli/bin/ng

> fsevents@1.2.8 install /Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/@angular/cli/node_modules/fsevents
> node install

node-pre-gyp WARN Using needle for node-pre-gyp https download
[fsevents] Success: "/Users/hayashiyoshino/.nodebrew/node/v11.0.0/lib/node_modules/@angular/cli/node_modules/fsevents/lib/binding/Release/node-v67-darwin-x64/fse.node" is installed via remote
+ @angular/cli@7.3.8
added 363 packages from 197 contributors in 14.724s


╭───────────────────────────────────────────────────────────────╮
│ │
New minor version of npm available! 6.4.1 6.9.0
Changelog: https://github.com/npm/cli/releases/tag/v6.9.0
Run npm install -g npm to update! │
│ │
╰───────────────────────────────────────────────────────────────╯

 

 

②npm install --save-dev @angular-devkit/build-angular

 "@angular-devkit/build-angular"というモジュールをインストールします。

$ npm install --save-dev @angular-devkit/build-angular

> fsevents@1.2.7 install /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/fsevents
> node install

node-pre-gyp WARN Using request for node-pre-gyp https download
[fsevents] Success: "/Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/fsevents/lib/binding/Release/node-v67-darwin-x64/fse.node" is installed via remote

> uws@9.148.0 install /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/uws
> node-gyp rebuild > build_log.txt 2>&1 || exit 0


> wd@1.11.1 install /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/wd
> node scripts/build-browser-scripts


> node-sass@4.11.0 install /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/node-sass
> node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.11.0/darwin-x64-67_binding.node
Download complete ⸩ ⠋ :
Binary saved to /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/node-sass/vendor/darwin-x64-67/binding.node
Caching binary to /Users/hayashiyoshino/.npm/node-sass/4.11.0/darwin-x64-67_binding.node

> ngrok@3.1.1 postinstall /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/ngrok
> node ./postinstall.js

ngrok - downloading binary https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip
ngrok - downloading progress: 14913520/14913520
ngrok - binary downloaded to /Users/hayashiyoshino/.ngrok/aHR0cHM6Ly9iaW4uZXF1aW5veC5pby9jLzRWbUR6QTdpYUhiL25ncm9rLXN0YWJsZS1kYXJ3aW4tYW1kNjQuemlw.zip
ngrok - unpacking binary
ngrok - binary unpacked to /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/ngrok/bin/ngrok

> node-sass@4.11.0 postinstall /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/node-sass
> node scripts/build.js

Binary found at /Users/hayashiyoshino/projects/tama/tamarubykaigi01/node_modules/node-sass/vendor/darwin-x64-67/binding.node
Testing binary
Binary is fine
+ @angular-devkit/build-angular@0.13.8
added 1436 packages from 1636 contributors and audited 50418 packages in 76.049s
found 4 vulnerabilities (2 low, 2 high)
run `npm audit fix` to fix them, or `npm audit` for details

 

③ng serve

これでng serveで動くようになります。

 $ ng serve
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

Date: 2019-04-28T05:53:27.600Z
Hash: 68661388f029a8b87102
Time: 9763ms
chunk {es2015-polyfills} es2015-polyfills.js, es2015-polyfills.js.map (es2015-polyfills) 284 kB [initial] [rendered]
chunk {main} main.js, main.js.map (main) 80.5 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 236 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 69.4 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 429 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.52 MB [initial] [rendered]
wdm: Compiled successfully.

 

 

Angular、個人でも触ってみたい気持ちになってきました!!

 

 

 

 

 

Date型のカラムの値が今日の日付より以前のレコードをとるのに苦戦した

発生した問題

Jobで以下のようにクライアントのidを取得している部分に対して、"今日の日付より以前の契約をしている"という条件も足したいと思いました。

client_ids = invoice_build.billing_closing_date.contracts.with_status(:actived).pluck(:client_id).uniq

これに where(“from > ?“, Date.today) を追加して以下のように書いたのですが、うまくクライアントidを取得できませんでした。。。

client_ids = @invoice_build.billing_closing_date.contracts.with_status(:actived).where( "from > ?",  Date.today ).pluck(:client_id).uniq

 

 

試したこと

コンソールでも似たような内容を試したのですが、以下のようなエラーが出てしまいました。。。

Contract.where('from < ?', Date.today).first

Contract Load (41.6ms) SELECT "contracts".* FROM "contracts" WHERE (from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1 [["LIMIT", 1]]
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "from"
LINE 1: SELECT "contracts".* FROM "contracts" WHERE (from < '2019-0...
^
: SELECT "contracts".* FROM "contracts" WHERE (from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1
from /Users/hayashiyoshino/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:614:in `async_exec'

 

以下のように、whereの条件をfromではなくcreated_atにするとうまく動いてくれるので書き方はあってそうな気がするのですが、fromに変えるとエラーとなっておりました。

Contract.where('created_at < ?', Date.today).first


fromカラムの型はdate型でしたので、以下のように比較するときちんとtrue返ってくれており、whereの時だけ比較できなくなってしまうみたいでした。。。

contract.from
=> Sat, 01 Dec 2018
[30] pry(main)> contract.from < Date.today
=> true

 

 

解決方法

テーブル名をつけることで、レコードを取得できるようになりました!!!

Contract.where("contracts.from < :from", from: Date.today).first
Contract Load (1.5ms) SELECT "contracts".* FROM "contracts" WHERE (contracts.from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<Contract:0x00007f8ffbdef138
id: 1,
client_id: 1036,
from: Sat, 01 Dec 2018,
>

 

 

感想その他

SQLの知識もActiveRecordの知識も足りていないので勉強してゆきます!!!

会社の先輩が貸してくれたSQLの本も読んでいこうと思います!!!