Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Forked from justinburdett/random-magic-cube.rb
Last active December 10, 2015 09:28
Show Gist options
  • Save steveklabnik/4414517 to your computer and use it in GitHub Desktop.
Save steveklabnik/4414517 to your computer and use it in GitHub Desktop.
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
@steveklabnik
Copy link
Author

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

    title =  html.xpath('//title').first.content.split("(").first

    file.puts "1 " + content
    puts "##{card_number + 1}: #{content}"

which is waaaay more clear. Don't do each loops over something that only has one element, unless sometimes you want more. :)

@steveklabnik
Copy link
Author

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