Class: LeanpubExtension

Inherits:
Middleman::Extension
  • Object
show all
Defined in:
lib/middleman-leanpub.rb

Defined Under Namespace

Classes: HttpError

Instance Method Summary collapse

Constructor Details

#initialize(app, options_hash = {}, &block) ⇒ LeanpubExtension

Returns a new instance of LeanpubExtension.



12
13
14
# File 'lib/middleman-leanpub.rb', line 12

def initialize(app, options_hash={}, &block)
  super
end

Instance Method Details

#after_configurationObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/middleman-leanpub.rb', line 16

def after_configuration
  uri = URI.parse("https://leanpub.com/#{options.book}.json?api_key=#{options.api_key}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri.request_uri)
  response = http.request(request)

  raise HttpError, response.body unless response.code.to_i == 200

  # Gimme dat JSON
  result = JSON.parse(response.body)
  
  filepath = File.join(app.root_path, app.config.data_dir, 'leanpub.yml')
  file = File.open(filepath, 'w') do |f|
    f.write("reader_count: #{result['total_copies_sold'].to_i}")
  end
rescue HttpError
  puts "Shit did not go well with LeanPub"
end