Module: LibMmini

Defined in:
lib/lib_mmini.rb

Constant Summary collapse

BACKEND_BASE =
'https://mmini.herokuapp.com'.freeze
BACKEND =
URI.parse(BACKEND_BASE + '/minify')
HTTP =
Net::HTTP.new(BACKEND.host, BACKEND.port = nil)

Instance Method Summary collapse

Instance Method Details

#parse_args(argv) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lib_mmini.rb', line 20

def parse_args(argv)
  options = OpenStruct.new
  options.url = nil

  OptionParser.new do |opts|
    opts.on_tail('-v', '--version', 'Show version') do
      puts LibVersion::VERSION
      exit
    end
  end.parse!

  if argv.length != 1
    puts 'Only single argument supported'
    exit
  end

  options[:url] = argv.first
  options.freeze
  options
end

#post_url(url) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/lib_mmini.rb', line 46

def post_url(url)
  header = { 'Content-Type': 'application/json' }
  body = {
    url: url
  }

  req = Net::HTTP::Post.new(BACKEND.request_uri, header)
  req.body = body.to_json

  HTTP.request(req)
end

#run(argv, post_url_fn) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/lib_mmini.rb', line 58

def run(argv, post_url_fn)
  args = parse_args(argv)
  url = args.url

  unless valid_url?(url)
    puts 'URL is invalid: ' + url
    exit!
  end

  response = post_url_fn.call(url)

  if response.code == '200'
    id = response.body
    success = true
    [success, BACKEND_BASE.to_s + '/' + id]
  else
    success = false
    [success, '']
  end
end

#valid_url?(string) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/lib_mmini.rb', line 41

def valid_url?(string)
  hits = string =~ /\A#{URI::DEFAULT_PARSER.make_regexp}\z/
  !hits.nil? && hits.zero?
end