Forked from justinburdett/random-magic-cube.rb
Last active
December 10, 2015 09:28
-
-
Save steveklabnik/4414517 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'nokogiri' | |
require 'open-uri' | |
class CardGenerator | |
def initialize(format) | |
@format = format | |
end | |
def random_card | |
html = "" | |
loop do | |
html = fetch_random_card_html | |
break unless is_card_illegal_for_format?(html) | |
end | |
Card.new(html) | |
end | |
class Card | |
def initialize(html) | |
@html = html | |
end | |
def title | |
title = @html.xpath('//title').first.content.split("(").first | |
end | |
end | |
private | |
def fetch_random_card_html | |
Nokogiri::HTML(open('http://magiccards.info/random.html')) | |
end | |
def is_card_illegal_for_format?(html) | |
html.css('li.legal') | |
.collect(&:content) | |
.select{|v| v =~ /#{@format}/} | |
.empty? | |
end | |
end | |
card_count = (ENV['COUNT'] || "360").to_i | |
format = ENV['FORMAT'] || "Vintage" | |
generator = CardGenerator.new(format) | |
File.open('random-cube.txt', 'w') do |file| | |
card_count.times do |card_number| | |
card = generator.random_card | |
file.puts "1 " + card.title | |
puts "##{card_number + 1}: #{card.title}" | |
end | |
end |
This version is super overkill, but if you wanted to start moving this logic into another application, this is how you'd do it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like pulling logic out into helper methods, so that the logic reads more cleanly.
If I was doing this again, I'd change lines 26-30 to
which is waaaay more clear. Don't do each loops over something that only has one element, unless sometimes you want more. :)