Faraday::Error: :hashie is not registered on Faraday::Middleware - ruby

I am creating a wrapper gem for a RESTful API. I am getting following error when I try to add hashie middleware as per the documentation:
Magpress::Login::#call#test_0001_should return valid JWT token:
Faraday::Error: :hashie is not registered on Faraday::Middleware
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday.rb:184:in `lookup_middleware'
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday/rack_builder.rb:204:in `use_symbol'
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday/rack_builder.rb:84:in `use'
/home/amit/projects/bt/magpress/lib/magpress/client.rb:24:in `block in connection'
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday/connection.rb:91:in `initialize'
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday.rb:70:in `new'
/home/amit/.rvm/gems/ruby-2.2.2#magpress/gems/faraday-0.10.0/lib/faraday.rb:70:in `new'
/home/amit/projects/bt/magpress/lib/magpress/client.rb:18:in `connection'
/home/amit/projects/bt/magpress/lib/magpress/base.rb:7:in `initialize'
/home/amit/projects/bt/magpress/test/login_spec.rb:13:in `new'
/home/amit/projects/bt/magpress/test/login_spec.rb:13:in `block (3 levels) in <top (required)>'
Here is how I delcared dependencies in .gemspec.
...
spec.add_dependency "faraday"
spec.add_dependency "faraday_middleware"
spec.add_dependency "hashie"
....
and the class that uses faraday and it's middleware
require 'faraday'
require 'faraday_middleware'
require 'hashie'
module Magpress
class Client
def connection(url)
conn = ::Faraday.new(url) do |faraday|
faraday.request :json
faraday.response :json, :content_type => /\bjson$/
# faraday.use :instrumentation
faraday.use :hashie # FaradayMiddleware::Mashify
faraday.adapter Faraday.default_adapter
end
conn
end
end
end
farady and middlware gem versions
amit#amit:~/projects/bt/magpress$ gem list | grep faraday
faraday (0.10.0)
faraday_middleware (0.10.1)
What could be wrong here?
If I replace :hashie with FaradayMiddleware::Mashify, the errors goes away but the response.body returns instance of vanilla Hash instead of
Hashie::Mash

Voila! It is fixed.
Current
faraday.response :json, :content_type !=> /\bjson$/
faraday.use :hashie # FaradayMiddleware::Mashify
After Fix
faraday.response :mashify
faraday.response :json, :content_type => /\bjson$/
I could fix by reading the code!

Related

Error after trying to access xml (Zlib::BufError) (Ruby)

I keep getting and error whenever I try and access an XML file in Ruby. This is my code:
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
require 'open-uri'
url = 'http://access.alchemyapi.com/calls'
service = '/text/TextGetRankedTaxonomy'
apikey = '?apikey=4317fce9281094613deee9ebcc5aaf5238cd0748'
thething = '&text='
text = 'men%27s%20white%20crew%20neck%20shirt'
fullurl = url + service + apikey + thething + text
opener = open(fullurl) {|f| f.read }
Here is the error:
C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:357:in `finish': buffer error (Zlib::BufError)
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:357:in `finish'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:262:in `ensure in inflater'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:262:in `inflater'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:274:in `read_body_0'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:201:in `read_body'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:226:in `body'
from C:/Ruby21/lib/ruby/2.1.0/net/http/response.rb:163:in `reading_body'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:1420:in `block in transport_request'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:1411:in `catch'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:1411:in `transport_request'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:1384:in `request'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:509:in `block in post_form'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:853:in `start'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:583:in `start'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:507:in `post_form'
from C:/Users/KVadher/Desktop/test151:11:in `<main>'
Is there anything I can do to either solve the error or run past it?
There is something wrong with the way this API server is encoding the data. To bypass this, you can simple say in the HTTP header that you don't accept any kind of encoding:
opener = open(fullurl, 'Accept-Encoding' => '') {|f| f.read }

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" }

Unable to find matching line from backtrace in ruby 2.0, rspec 3.0

I got this error when running a feature spec using rspec 3.0, ruby 2.0.0p195 on Windows in Rails 4.0. Reading on Googles, I find that a fix was to use a specific version in rpsec 2.0 but nothing past that version. I thought I would have been long past that issue. Like others, I find that when I manually act out the steps of the feature, everything works as expected. There is no indicator of what line of the spec fails. Where should I look in Google to get past this issue? Or have I made a goof somewhere?
gemfile.lock
rspec-core (3.0.2)
rspec-support (~> 3.0.0)
rspec-expectations (3.0.2)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.0.0)
rspec-mocks (3.0.2)
rspec-support (~> 3.0.0)
rspec-rails (3.0.1)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
rspec-core (~> 3.0.0)
rspec-expectations (~> 3.0.0)
rspec-mocks (~> 3.0.0)
rspec-support (~> 3.0.0)
rspec-support (3.0.2)
Fails here: _score_form.html.erb
<%= simple_form_for [#site, #inspection, score] do |f| %>
<%= f.input :note %>
<%= f.button :submit, submit_text %>
<% end %>
<a class="close-reveal-modal">×</a>
note_feature_spec.rb
require 'spec_helper'
feature "notes", js: true do
background do
#surveys = ["Loss", "Solutions"]
#manager = FactoryGirl.create(:manager)
#site = FactoryGirl.create(:site)
#user = FactoryGirl.create(:user, site_id: #site.id)
#survey = FactoryGirl.create(:survey, name: "#{#surveys[1]}", user_id: #manager.id)
#item_1 = FactoryGirl.create(:item, name: "item 1", survey_id: #survey.id, category: "Regular", sub_category:
'DEC')
#variance = FactoryGirl.create(:cash_variance)
end
scenario "appear when saved with a score" do
visit root_path
click_link 'Login'
fill_in 'Email', with: #manager.email
fill_in 'Password', with: #manager.password
click_button 'Log in'
click_link ("#{#site.name}" + " #{#site.site_type}")
click_link 'New Inspection'
select("#{#survey.name}")
click_button 'Start inspection'
score = Score.where(inspection_id: Inspection.last.id, item_id: #item_1.id).first
expect(page).to have_content("#item.name")
expect(page).to have_css("note-act#{#score.id}")
end
end
relevant portion of scores_controller.rb
class ScoresController < ApplicationController
def update
#site = Site.find(params[:site_id])
#inspection = #site.inspections.find(params[:inspection_id])
#score = #inspection.scores.find(params[:id])
respond_to do |format|
if #score.update_attributes(score_params)
format.html {redirect_to edit_site_inspection_path(#site,#inspection), notice: 'Score was updated'}
format.json {head :no_content}
format.js
else
format.html { render action: 'edit'}
format.json { render json: #score.errors, status: :unprocessable_entity }
end
end
end
Top of error message:
1) notes it appears when saved with a score
Failure/Error: Unable to find matching line from backtrace
ActionView::Template::Error:
undefined method `note' for #<Score:0x8acdb60>
# ./app/views/inspections/_score_form.html.erb:2:in `block in _app_views_inspections__score_form_html_erb__524083191_68481552'
# ./app/views/inspections/_score_form.html.erb:1:in `_app_views_inspections __score_form_html_erb__524083191_68481552'
# ./app/views/inspections/_regular.html.erb:13:in `_app_views_inspections__regular_html_erb__743764807_72723960'
# ./app/views/inspections/_clean_scores.html.erb:17:in `block (3 levels) in _app_views_inspections__clean_scores_html_erb___604997166_72361188'
# ./app/views/inspections/_clean_scores.html.erb:15:in `each'
# ./app/views/inspections/_clean_scores.html.erb:15:in `block (2 levels) in
It turns out there is a migration missing, so it is as I suspected: a goof.

Sinatra fails to answer to a very basic GET request

I have the following Gemfile:
source "http://rubygems.org"
gem 'sinatra', '1.3.2'
gem 'json', '1.6.4'
And the following Sinatra application:
require 'sinatra'
require 'json'
get '/ze/api/session.json' do
content_type :json
{ :name => 'name' }
end
And when I make a basic request like this one:
curl localhost:4567/ze/api/session.json
I get this:
[2012-01-13 17:30:36] ERROR TypeError: can't convert Array into String
/Users/mauricio/.rvm/gems/ruby-1.9.2-p290#office-drop-sync/gems/rack-1.4.0/lib/rack/handler/webrick.rb:72:in `block in service'
/Users/mauricio/.rvm/gems/ruby-1.9.2-p290#office-drop-sync/gems/rack-1.4.0/lib/rack/handler/webrick.rb:71:in `each'
/Users/mauricio/.rvm/gems/ruby-1.9.2-p290#office-drop-sync/gems/rack-1.4.0/lib/rack/handler/webrick.rb:71:in `service'
/Users/mauricio/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/Users/mauricio/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/Users/mauricio/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
localhost - - [13/Jan/2012:17:30:36 BRT] "GET /ze/api/session.json HTTP/1.1" 500 311
I am using Ruby 1.9.2 with RVM in a Lion Mac.
You're trying to return a hash from the route, but a hash isn't something you can return here.
Simply use .to_json to turn the hash into a json string which you can then return (you've required json, but aren't using it yet):
get '/ze/api/session.json' do
content_type :json
{ :name => 'name' }.to_json
end

Can't use facebook to authenticate: undefined method 'web_server' for OAuth2?

Trying to let users sign in / sign up with Twitter and Facebook. Twitter works no problem but the strategy is different for Facebook.
undefined method `web_server' for #<OAuth2::Client:0x00000005211d58>
Trace shows
oa-oauth (0.0.1) lib/omniauth/strategies/oauth2.rb:18:in `request_phase'
oa-oauth (0.0.1) lib/omniauth/strategies/facebook.rb:28:in `request_phase'
oa-core (0.0.5) lib/omniauth/strategy.rb:25:in `call!'
oa-core (0.0.5) lib/omniauth/strategy.rb:19:in `call'
oa-core (0.0.5) lib/omniauth/builder.rb:22:in `call'
warden (1.0.5) lib/warden/manager.rb:35:in `block in call'
warden (1.0.5) lib/warden/manager.rb:34:in `catch'
warden (1.0.5) lib/warden/manager.rb:34:in `call'
Anybody else experienced this?
ps. I'm using the following gems:
gem 'oa-oauth', :require => 'omniauth/oauth'
gem 'oauth2'
I'm not using the full omniauth gem as its addressable dependencies conflict with other gems.
I ran into the same problem when trying to use facebook_oauth (https://github.com/moomerman/facebook_oauth) on my rails app. After spending an hour or so trying to change its code, i realized it might be easier just to use oauth2 directly. I solved the problem and now there's no need for that intermediate library. Here's how:
In Gemfile add
gem 'oauth2'
Then run
bundle update
Then, in your login_via_facebook method you either construct the dialog uri manually or use the oauth client something along these lines:
oauth_client = OAuth2::Client.new(APPLICATION_ID, APPLICATION_SECRET, {
:authorize_url => 'https://www.facebook.com/dialog/oauth'
})
redirect_to oauth_client.authorize_url({
:client_id => APPLICATION_ID,
:redirect_uri => YOUR_REDIRECT_URL
})
If you need to request additional permissions, specify scope param in the authorize_url call:
redirect_to oauth_client.authorize_url({
:client_id => APPLICATION_ID,
:redirect_uri => YOUR_REDIRECT_URL,
:scope => 'offline_access,email'
})
Then, in the method that handles YOUR_REDIRECT_URL (i call mine login_via_facebook_callback), do something like this:
oauth_client = OAuth2::Client.new(APPLICATION_ID, APPLICATION_SECRET, {
:site => 'https://graph.facebook.com',
:token_url => '/oauth/access_token'
})
begin
access_token = oauth_client.get_token({
:client_id => APPLICATION_ID,
:client_secret => APPLICATION_SECRET,
:redirect_uri => YOUR_REDIRECT_URL,
:code => params[:code],
:parse => :query
})
access_token.options[:mode] = :query
access_token.options[:param_name] = :access_token
facebook_user_info = access_token.get('/me', {:parse => :json}).parsed
rescue Error => e
# You will need this error during development to make progress :)
#logger.error(e)
end
Now facebook_user_info has the basic user info!
I had a similar issue, you should try two things:
I also had conflicting gem issues/dependencies issues and resolved them by adding this in my gemfile:
gem 'omniauth', :git => 'git://github.com/intridea/omniauth.git'
Try using a rails application template which works remarkably well for starting a Twitter/Facebook app in no time, run this command in your terminal:
rails new APP_NAME -m https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-mongoid-omniauth-template.rb -T
You can read more about it here:
https://github.com/RailsApps/rails3-mongoid-omniauth/wiki/Tutorial
here i came across an example app that demonstrates the use of omniauth along with authlogic
https://github.com/madhums/omniauth-authlogic-demo
hope it helps

Resources