Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bin/embedly_objectify

This file was deleted.

12 changes: 12 additions & 0 deletions bin/embedly_objectify
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env ruby
$:.unshift(File.expand_path('../../lib', __FILE__))
%w{embedly embedly/command_line json optparse ostruct}.each {|l| require l}

api = Embedly::CommandLine.run!(:objectify, ARGV)

begin
data = api.flatten.collect { |o| o.marshal_dump }
puts JSON.pretty_generate(data)
rescue Embedly::BadResponseException => e
puts "#{e.response.code} :: #{e.response.message}"
end
91 changes: 4 additions & 87 deletions bin/embedly_oembed
Original file line number Diff line number Diff line change
@@ -1,95 +1,12 @@
#!/usr/bin/env ruby
$:.unshift(File.expand_path('../../lib', __FILE__))
%w{embedly json optparse ostruct}.each {|l| require l}
%w{embedly embedly/command_line json optparse ostruct}.each {|l| require l}

options = OpenStruct.new({
:hostname => nil,
:key => ENV['EMBEDLY_KEY'] == '' ? nil : ENV['EMBEDLY_KEY'],
:secret => ENV['EMBEDLY_SECRET'] == '' ? nil : ENV['EMBEDLY_SECRET'],
:verbose => false,
:args => {},
:headers => {}
})
api = Embedly::CommandLine.run!(:oembed, ARGV)

action = File.basename(__FILE__)[/embedly_(\w+)/, 1]

opts = OptionParser.new do |opts|
opts.banner = <<-DOC
Fetch JSON from the embedly #{action} service.
Usage #{action} [OPTIONS] <url> [url] ..
DOC

opts.separator ""
opts.separator "Options:"

opts.on("-H", "--hostname ENDPOINT",
"Embedly host. Default is api.embed.ly.") do |e|
options.hostname = e
end

opts.on("--header NAME=VALUE",
"HTTP header to send with requests.") do |header|
n,v = header.split '='
options.headers[n] = v
end

opts.on("-k", "--key KEY", "Embedly key [default: " +
"EMBEDLY_KEY environmental variable]") do |k|
options.key = k
end

opts.on("-s", "--secret SECRET", "Embedly secret [default: " +
"EMBEDLY_SECRET environmental variable]") do |s|
options.secret = s
end

opts.on("-N", "--no-key", "Ignore EMBEDLY_KEY environmental variable") do
options.key = nil
end

opts.on("--no-secret", "Ignore EMBEDLY_SECRET environmental variable") do
options.secret = nil
end

opts.on("-o", "--option NAME=VALUE", "Set option to be passed as " +
"query param.") do |o|
k,v = o.split('=')
options.args[k] = v
end

opts.separator ""
opts.separator "Common Options:"

opts.on("-v", "--verbose", "Run verbosely") do
options.verbose = true
end

opts.on("-h", "--help", "Display this message") do
puts opts
exit
end

opts.separator ""
opts.separator "Bob Corsaro <bob@embed.ly>"
end

opts.parse!

if ARGV.size < 1
$stderr.puts "ERROR: url required"
$stderr.puts opts
exit 1
end

Embedly::Config.logging = true if options.verbose

options.args[:urls] = ARGV
api = Embedly::API.new options.marshal_dump
begin
objs = [api.send(action.to_sym, options.args)].flatten.collect{|o| o.marshal_dump}
puts JSON.pretty_generate(objs)
data = api.flatten.collect { |o| o.marshal_dump }
puts JSON.pretty_generate(data)
rescue Embedly::BadResponseException => e
puts "#{e.response.code} :: #{e.response.message}"
end


1 change: 0 additions & 1 deletion bin/embedly_preview

This file was deleted.

12 changes: 12 additions & 0 deletions bin/embedly_preview
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env ruby
$:.unshift(File.expand_path('../../lib', __FILE__))
%w{embedly embedly/command_line json optparse ostruct}.each {|l| require l}

api = Embedly::CommandLine.run!(:preview, ARGV)

begin
data = api.flatten.collect { |o| o.marshal_dump }
puts JSON.pretty_generate(data)
rescue Embedly::BadResponseException => e
puts "#{e.response.code} :: #{e.response.message}"
end
126 changes: 126 additions & 0 deletions lib/embedly/command_line.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
require "optparse"

module Embedly
class CommandLine

class Parser
attr_accessor :options

def initialize(args)
@options, @args = default, args
end

def parse!
parser.parse!(@args)
set_urls!
reject_nil!
options
rescue OptionParser::InvalidOption => error
puts "ERROR: #{error.message}"
puts parser.on_tail
exit
end

def self.parse!(args)
new(args).parse!
end

private

def default
{
:key => ENV['EMBEDLY_KEY'],
:secret => ENV['EMBEDLY_SECRET'],
:headers => {},
:query => {}
}
end

def reject_nil!
options.reject! { |_, opt| opt.nil? }
end

def set_urls!
raise(OptionParser::InvalidOption, "url required") if @args.empty?
options[:query][:urls] = @args
end

def parser
OptionParser.new do |parser|
parser.banner = %{
Fetch JSON from the embedly service.
Usage [OPTIONS] <url> [url] ..
}

parser.separator ""
parser.separator "Options:"

parser.on('-H', '--hostname ENDPOINT', 'Embedly host. Default is api.embed.ly.') do |hostname|
options[:hostname] = hostname
end

parser.on("--header NAME=VALUE", "HTTP header to send with requests.") do |hash|
header, value = hash.split '='
options[:headers][header] = value
end

parser.on("-k", "--key KEY", "Embedly key [default: EMBEDLY_KEY environmental variable]") do |key|
options[:key] = key
end

parser.on("-N", "--no-key", "Ignore EMBEDLY_KEY environmental variable") do |key|
options[:key] = nil
end

parser.on("-s", "--secret SECRET", "Embedly secret [default: EMBEDLY_SECRET environmental variable]") do |secret|
options[:secret] = secret
end

parser.on("--no-secret", "Ignore EMBEDLY_SECRET environmental variable") do
options[:secret] = nil
end

parser.on("-o", "--option NAME=VALUE", "Set option to be passed as query param.") do |option|
key, value = option.split('=')
options[:query][key.to_sym] = value
end

parser.separator ""
parser.separator "Common Options:"

parser.on("-v", "--[no-]verbose", "Run verbosely") do |verbose|
Embedly::Config.logging = verbose
end

parser.on("-h", "--help", "Display this message") do
puts parser
exit
end

parser.separator ""
parser.separator "Bob Corsaro <bob@embed.ly>"
end
end
end

class << self
def run!(endpoint, args = [])
new(args).run(endpoint)
end
end

def initialize(args)
@options, @args = {}, args
end

def run(endpoint = :oembed)
api_options = options.dup
query = api_options.delete(:query)
Embedly::API.new(api_options).send(endpoint, query)
end

def options
@options = Parser.parse!(@args.dup)
end
end
end
118 changes: 118 additions & 0 deletions spec/embedly/command_line_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
require "spec_helper"
require "embedly/command_line"

module Embedly
describe CommandLine do
after do
ENV['EMBEDLY_KEY'] = nil
ENV['EMBEDLY_SECRET'] = nil
end

describe "::run!" do
let(:arguments) { ['-k', 'MY_KEY', 'http://yfrog.com/h7qqespj', '-o', 'maxwidth=10'] }
let(:api) { mock(API) }

it "calls api with options" do
API.should_receive(:new).with(:key => 'MY_KEY', :headers => {}) { api }
api.should_receive(:oembed).with(:urls => ['http://yfrog.com/h7qqespj'], :maxwidth => '10')
CommandLine.run!(:oembed, arguments)
end

it "raises an error if the arguments are empty" do
$stdout = StringIO.new
expect {
CommandLine.run!(:oembed, [])
}.to raise_error(SystemExit)
end
end

describe "#run" do
before do
API.any_instance.stub(:oembed)
end

describe "with option --hostname" do
%w[-H --hostname].each do |option|
it "sets the hostname using #{option}" do
command([option, "sth.embed.ly"])[:hostname].should == 'sth.embed.ly'
end
end
end

describe "with --header" do
it "sets the header" do
command(%w[--header Header=value])[:headers].should == { 'Header' => 'value' }
end
end

describe "with --key" do
%w[-k --key].each do |option|
it "sets the key using #{option}" do
command([option, "SOME_KEY"])[:key].should == 'SOME_KEY'
end
end

it "gets the key from environment variables if no key was set" do
ENV['EMBEDLY_KEY'] = 'ENVIRONMENT_KEY'

command([])[:key].should == 'ENVIRONMENT_KEY'
end
end

describe "with --secret" do
%w[-s --secret].each do |option|
it "sets the secret using #{option}" do
command([option, "SECRET"])[:secret].should == 'SECRET'
end
end

it "gets the secret from environment variables if no secret was set" do
ENV['EMBEDLY_SECRET'] = 'ENVIRONMENT_SECRET'

command([])[:secret].should == 'ENVIRONMENT_SECRET'
end
end

describe "with --no-key" do
%w[-N --no-key].each do |option|
it "unsets the key using #{option}" do
command([option])[:key].should be_nil
end
end
end

describe "with --no-secret" do
it "unsets the secret" do
command(['--no-secret'])[:secret].should be_nil
end
end

describe "with --option" do
%w[-o --option].each do |option|
it "sets custom option with #{option}" do
command([option, "maxwidth=100"])[:query][:maxwidth].should == '100'
end
end
end

describe "with --verbose" do
it "enables logging" do
command(["--verbose"])
Embedly::Config.logging.should be_true
end

it "disables logging" do
command(["--no-verbose"])
Embedly::Config.logging.should be_false
end
end
end

def command(arguments)
arguments << 'testurl.com'
command = CommandLine.new(arguments)
command.run
command.options
end
end
end
1 change: 1 addition & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require "embedly"