0r4cl3
0r4cl3

Reputation: 132

Use instance method from other class

I created a class that returns the local time of cities.

class GetTime
  def london
    #some code
  end

  def newyork
    #some code
  end
end

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

Let's imagine I have a shop on each city that is open 9 to 17 and I want to determine if this shop is open. I defined the class MarketOpen. I would like to call its method is_open? on an instance of GetTime. The method should return true if the time returned from time.london is between 9 to 17.

class MarketOpen
  def is_open?
    #some code
  end
end

time.london.is_open?

Is this achievable? Would it be a good practice? What would be the best approach to call a method from another class?

Upvotes: 0

Views: 113

Answers (1)

spickermann
spickermann

Reputation: 106882

I am not convinced that GetTime is a usefull model, but I will keep it unchanged in this example. Then I would change Shop to something like this:

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

The following should return your expected result:

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

Update: I would implement the local time calculation using 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

Using this implementation would allow to change the private local_time method in my answer to:

def local_time
  LocalTime.for(location)
end

Upvotes: 2

Related Questions