public
Created

DIP snippet 2

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
class Game < ActiveRecord::Base
belongs_to :category
validates_presence_of :title, :category_id, :description,
:price, :platform, :year
end
 
class GamePriceService
attr_accessor :game, :json_parser
 
# we could use a config file
BASE_URL = "http://thegamedatabase.com/api/game"
API_KEY = "ek2o1je"
 
def initialize(game, json_parser = JsonParserLib)
self.game = game
self.json_parser = json_parser
end
 
def get_price
data = open("#{BASE_URL}/#{game.name}/price?api_key=#{API_KEY}")
json_parser.parse(data)
end
end
 
class GamePrinter
attr_accessor :game, :game_webservice
 
def initialize(game, game_webservice = GamePriceService)
self.game = game
self.game_webservice = game_webservice
end
 
def print
price_service = game_webservice.new(game)
<<-EOF
#{game.name}, #{game.platform}, #{game.year}

current value is #{price_service.get_price[:value]}
EOF
end
end
 
# Usage example:
game = Game.new(some_game_data)
webservice = GamePriceService.new(game)
game.price = webservice.get_price
 
GamePrinter.new(game).print

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.