使用其他类的实例方法

时间:2015-10-16 15:49:31

标签: ruby

我创建了一个返回城市当地时间的课程。

class GetTime
  def london
    #some code
  end

  def newyork
    #some code
  end
end

time = GetTime.new
time.london # => 2015-10-16 10:46:54

让我们想象一下,每个城市都有一家商店,营业时间为9到17,我想确定这家商店是否开放。我定义了班级MarketOpen。我想在is_open?的实例上调用它的方法GetTime。如果从true返回的时间介于9到17之间,则该方法应返回time.london

class MarketOpen
  def is_open?
    #some code
  end
end

time.london.is_open?

这可以实现吗?这是一个好习惯吗?从另一个类调用方法的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

我不相信GetTime是一个有用的模型,但在这个例子中我将保持不变。然后我会将Shop更改为类似的内容:

class Shop
  attr_reader :location

  def initialize(location)
    @location = location
  end

  def open?
    # some code checking `local_time` against opening hours
  end

private

  def local_time
    time = GetTime.new
    time.send(location)
  end
end

以下内容应返回您的预期结果:

shop = Shop.new('London')
shop.open?

更新:我会使用Time#getlocal实施本地时间计算:

class LocalTime
  attr_reader :time

  ZONES = {
    'Tokyo'    => '+09:00',
    'Berlin'   => '+01:00'
    'London'   => '+00:00',
    'New York' => '-05:00'
    # ...
  }

  def self.for(location)
    new.for(location)
  end

  def initialize
    @time = Time.now
  end

  def for(location)
    offset = ZONES.fetch(location)
    time.getlocal(offset)
  end

end

使用此实现可以在我的答案中更改私有local_time方法:

def local_time
  LocalTime.for(location)
end