How to use mocha outside of unit tests? - ruby

I'm trying to use mocha outside of unit tests to mock an Net::HTTPResponse object. here is a simple example:
#!/usr/bin/env ruby -w
require 'net/http'
require 'rubygems'
require 'mocha'
response = mock('Net::HTTPResponse')
response.stubs(:code => '500', :message => "Failed", :content_type => "text/plaint", :body => '')
I get this error:
undefined method `mock' for main:Object (NoMethodError)

I'd recommend using the fakeweb gem for this. It's designed to stub out http requests.
require 'rubygems'
require 'fakeweb'
FakeWeb.register_uri(:get, "http://something.com/", :body => "", :status => ["500", "Server Error"])
More info: https://github.com/chrisk/fakeweb

Related

How to use Net::LDAP with JRuby

I am using Ruby and JRuby on a Ubuntu machine through RVM.
OpenLDAP is connecting and doing the CRUD operation through Ruby code with the Net::LDAP gem perfectly.
Here is the code:
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new :host => 'locahost',
:port => 389,
:async => 1,
:keepalive => 1,
:auth => {
:method => :simple,
:username => "cn=admin,dc=test,dc=com",
:password => "secret"
}
puts ldap.bind
When I execute the same code with JRuby, it throws an error:
$ jruby ldap_test.rb
ArgumentError: unsupported protocol family `__UNKNOWN_CONSTANT__'
initialize at org/jruby/ext/socket/RubySocket.java:188
new at org/jruby/RubyIO.java:847

Ruby: How to access an api using HTTParty

I'm new to Ruby, and to using HTTParty, and was trying to follow the HTTParty examples from their github page to execute a basic POST. When I run the code below I get an error:
require 'pp'
require 'HTTParty'
require 'pry'
class Partay
include HTTParty
base_uri "http://<myapidomain>/search/semanticsearch/query/"
end
options= {
query: {
version: "0.4",
query: "lawyer"
}}
response = Partay.post(options)
puts response
The error I get is:
rbenv/versions/2.2.0/lib/ruby/2.2.0/uri/common.rb:715:in `URI': bad argument (expected URI object or URI string) (ArgumentError)
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/httparty/request.rb:47:in `path='
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/httparty/request.rb:34:in `initialize'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:539:in `new'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:539:in `perform_request'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:491:in `post'
from json-to-csv.rb:16:in `<main>'
What I am looking for is calling a post that receives JSON in the same way that calling this URL works:
http://somedomain.com/search/semanticsearch/query/?version=0.4&query=lawyer
Noting a solution with the suggested gem - unirest:
require 'unirest'
url = "http://somedomain.com/search/semanticsearch/query"
response = Unirest.post url,
headers:{ "Accept" => "application/json" },
parameters:{ :version => 0.4, :query => "lawyer" }

modular Sinatra App, setting error handling & configuration globally

I am using Sinatra to build a small Ruby API, and I would like to get some of the errors and configurations set to work at a global level so that i don't need to set them at the start of each of the classes.
My structure is this:
content_api.rb
require 'sinatra/base'
require 'sinatra/namespace'
require 'sinatra/json'
require 'service_dependencies'
require 'api_helpers'
require 'json'
module ApiApp
class ContentApi < Sinatra::Base
helpers Sinatra::JSON
helpers ApiApp::ApiHelpers
include ApiApp::ServiceDependencies
before do
content_type :json
end
get '/' do
content = content_service.get_all_content
content.to_json
end
get '/audio' do
package =content_service.get_type 'Audio'
package.to_json
end
get '/video' do
package =content_service.get_type 'Video'
package.to_json
end
get '/document' do
package =content_service.get_type 'Document'
package.to_json
end
end
end
config.ru:
$LOAD_PATH.unshift *Dir[File.join(File.dirname(__FILE__), '/src/**')]
$LOAD_PATH.unshift *Dir[File.join(File.dirname(__FILE__), '/src/api/**')]
require 'content_api'
require 'package_api'
require 'utility_api'
require 'sinatra/base'
configure do
set :show_exceptions => false
end
error { |err| Rack::Response.new([{'error' => err.message}.to_json], 500, {'Content-type' => 'application/json'}).finish }
Rack::Mount::RouteSet.new do |set|
set.add_route ApiApp::ContentApi, {:path_info => %r{^/catalogue*}}, {}, :catalogue
set.add_route ApiApp::PackageApi, {:path_info => %r{^/package*}}, {}, :package
set.add_route ApiApp::UtilityApi, {:path_info => %r{^/health_check*}}, {}, :health_check
end
When I run this, it will run okay, but when I force a 500 error (shut down MongoDb) I get a standard html type error that states:
<p id="explanation">You're seeing this error because you have
enabled the <code>show_exceptions</code> setting.</p>
If I add the
configure do
set :show_exceptions => false
end
error { |err| Rack::Response.new([{'error' => err.message}.to_json], 500, {'Content-type' => 'application/json'}).finish }
inside the content_api.rb file, then I get a JSON error returned as I would like to receive.
however, as I am building this modular, I don't want to be repeating myself at the top of each class.
Is there a simple way to make this work?
The simplest way to do this would be to reopen Sinatra::Base and add the code there:
class Sinatra::Base
set :show_exceptions => false
error { |err|
Rack::Response.new(
[{'error' => err.message}.to_json],
500,
{'Content-type' => 'application/json'}
).finish
}
end
This is probably not advisable though, and will cause problems if your app includes other non-json modules.
A better solution might be to create a Sinatra extension that you could use in your modules.
module JsonExceptions
def self.registered(app)
app.set :show_exceptions => false
app.error { |err|
Rack::Response.new(
[{'error' => err.message}.to_json],
500,
{'Content-type' => 'application/json'}
).finish
}
end
end
You would then use it by registering it in your modules:
# require the file where it is defined first
class ContentApi < Sinatra::Base
register JsonExceptions
# ... as before
end
As an alternative, inheritance:
class JsonErrorController < Sinatra::Base
configure do
set :show_exceptions => false
end
error { |err| Rack::Response.new([{'error' => err.message}.to_json], 500, {'Content-type' => 'application/json'}).finish }
end
class ContentApi < JsonErrorController
# rest of code follows…
end
From Sinatra Up and Running p73:
Not only settings, but every aspect of a Sinatra class will be
inherited by its subclasses. This includes defined routes, all the
error handlers, extensions, middleware, and so on.

undefined method `batch_change_message_visibility' with AWS-SDK for Ruby

I'm trying to write a ruby script to change a message error but I'm getting the error batch_change_message_visibility is not a defined method.
Here is the code :
require 'rubygems'
require 'aws-sdk'
sqs = AWS::SQS.new(
:access_key_id => access_key,
:secret_access_key => access_secret)
queue = sqs.queues.named(queue_name)
messages = []
messages << { :message => message_handle, :visibility_timeout => 5 }
queue.batch_change_message_visibility(messages)
Any idea ? Thanks !
The method is called batch_change_visibility - the documentation has the wrong method name.

sinatra ruby in question

How to do that I have got resource in sinatra
http://localhost:port/resource.json ??
Install the json gem:
sudo gem install json
then just
require 'json'
get '/resource.json' do
content_type :json
{ :name => 'Michal', :location => 'unknown' }.to_json
end

Resources