クラス変数("@@")やめとけってよ

クラス変数("@@")使う人あんまりいないと思うけど、グローバル変数と同じようなもんだから使うなよっていう話。

Effective Ruby

Effective Ruby

項目15 クラス変数よりもクラスインスタンス変数を使うようにしよう

クラス変数を使ってSingletonを実装してみる

一見いい感じ。

class Singleton
  private_class_method(:new, :dup, :clone)

  def self.instance
    @@single ||= new
  end
end

でもサブクラスだとNG

全てのサブクラス間で共有されてしまう。

class Configuration < Singleton; end
class Database < Singleton; end

>> Configuration.instance
#<Configuration:0x00007fed1a890c88>

# NG: Configurationになっちゃう
>> Database.instance
#<Configuration:0x00007fed1a890c88>

解決方法:クラスインスタンス変数

「クラスメソッド内でインスタンス変数?」となるかもしれないが、クラスもオブジェクト。

class Singleton
  private_class_method(:new, :dup, :clone)

  def self.instance
    # @@ -> @に変更するだけ
    @single ||= new
  end
end

おまけ

スレッドを考慮すると上記実装では不十分。標準ライブラリのSingletonを使うと良い。

require "singleton"

class Configuration
  include Singleton
end

覚えておくべき事項

  • クラス変数よりもインスタンス変数を使うようにしよう。
  • クラスはオブジェクトなので、専用のプライベートなインスタンス変数セットを持っている。

MacのCPU温度を調べる方法

少し前に古いMacoBook AirからMac Bookに乗り換えたんだけど、Mac本体が結構熱くなってヤキモキしています。
とりあえず、CPU温度を測るツールを導入して見ました。


 

iStats

なんとRubygemsで公開されていました。見た目が良い。
Chris911/iStats: Ruby gem for your mac stats

f:id:rochefort:20180221113432p:plain

ソースをのぞいてみると

iStats/smc.c at master · Chris911/iStats
CのコードでMacAPIを叩いているようです。
なるほど、やっぱそうだよね。

Bitbarプラグイン

iStatsの結果をbitbar を使ってメニューバーに表示させようかと思ったのですが、すでにプラグインがあるのでは?と思って検索してみると以下がありました。
CPU Temperature on BitBar - Put anything in your Mac OS X menu bar
 
なんとこちらは、懐かしのsmcFanControlのバイナリを流用しているようです。

# 'smc' can be downloaded from: http://www.eidac.de/smcfancontrol/smcfancontrol_2_4.zip
# One-liner:
# curl -LO http://www.eidac.de/smcfancontrol/smcfancontrol_2_4.zip && unzip -d temp_dir_smc smcfancontrol_2_4.zip && cp temp_dir_smc/smcFanControl.app/Contents/Resources/smc /usr/local/bin/smc ; rm -rf temp_dir_smc smcfancontrol_2_4.zip

そしてキモい整形をしています。

$ smc -k TC0P -r | sed 's/.*bytes \(.*\))/\1/' |sed 's/\([0-9a-fA-F]*\)/0x\1/g' | perl -ne 'chomp; ($low,$high) = split(/ /); print (((hex($low)*256)+hex($high))/4/64); print "\n";'
59.0625

 
とりあえず、間隔が5sになっていたのを変更し、このプラグインを使っているところです。
f:id:rochefort:20180221113519p:plain

 

余談

App Storeで探して見たら、おしゃれなシステムメトリクス表示ができる Monit というNotificationツールがあったので購入して見ました。$3です。

MONIT

MONIT

  • Tildeslash
  • ユーティリティ
  • ¥360

 
ただ、こちらはCPUの温度計測はできないみたい。ですが、見た目がいいので気に入っています。
f:id:rochefort:20180221113754p:plain

Rubyのprotectedの使いどころ

Rubyのprivate/protectedは特殊で誰しもが混乱する設計の一つです。
そんなprotectedの使い所について書かれています。
 

Effective Ruby

Effective Ruby

項目14 protectedメソッドを使ってプライベートな状態を共有しよう

カプセル化が邪魔になるケース

他のオブジェクトの内部状態にアクセスしなければならない場合。
instance_eval使えばいけるけど、、、

class Widget
  # 他のobjectと座標が重なっているかチェックする場合など
  def overlapping?(other)
    x1, y1 = @screen_x, @screen_y
    x2, y2 = other.instance_eval { [@screen_x, @screen_y] }
  end
end

protectedで解決

class Widget
  def overlapping?(other)
    x1, y1 = @screen_x, @screen_y
    x2, y2 = other.screen_coordinates
  end

  protected
    def screen_coordinates
      [@screen_x, @screen_y]
    end
end

覚えておく事項

  • プライベートな状態はprotectedメソッドで共有できる
  • レシーバを明示してprotectedメソッドを呼び出せるのは、同じクラスのオブジェクトか共通のスーパークラスからprotectedメソッドを継承しているオブジェクトだけだ。

一応private/protectedのおさらい

privateはサブクラスからも呼べます。それってJavaでいうprotectedでは?と思いますが、 ここの違いは、インスタンス経由で呼べるかどうかです。
サブクラスのインスタンスから呼べるのがprotected、呼べないのがprivateと。
 

class Person
  protected
    def protected_method
      puts "Person#protected_method"
    end

  private
    def private_method
      puts "Person#private_method"
    end
end

class Runner < Person
  # ok(これはいいよね)
  def call_protected_method
    protected_method
  end

  # ok(これが呼べちゃう)
  def call_private_method
    private_method
  end

  # ok(インスタンスのprotectedなのでok)
  def call_instance_protected_method(instance)
    instance.protected_method
  end

  # ng(インスタンスのprivateなのでng)
  def call_instance_private_method(instance)
    instance.private_method
  end
end

>> r1 = Runner.new
>> r2 = Runner.new
>> r1.call_protected_method
Person#protected_method
>> r1.call_private_method
Person#private_method


>> r1.call_instance_protected_method(r2)
Person#protected_method
>> r1.call_instance_private_method(r2)
NoMethodError (private method `private_method' called for #<Runner:0x00007fed1a8818f0>

まとめ

プライベートな状態はprotectedメソッドで共有できることと、 privateは明示的なレシーバを用いて呼び出せないと覚えておけば良い。