API Errors Customization for Rails 3 Like Github API V3

How can I customize Rails 3 validation error json output?

On your model you can modify the way as json operates. For instance let us assume you have a ActiveRecord model Contact. You can override as_json to modify the rendering behavior.

def Contact < ActiveRecord::Base

def as_json
hash = super

hash.collect {|key, value|
{"field" => key, "code" => determine_code_from(value)}
}
end

end

Of course, you could also generate the json in a separate method on Contact or even in the controller. You would just have to alter your render method slightly.

render @contact.as_my_custom_json

How to get authenticated API request limits from the GitHub API using Ruby

The issue seem to have more to do with poor Ruby documentation maintenance, it seem mostly obscured with outdated solutions. The other most common issue is, that in the examples I gave (found) they never handle SSL (HTTPS) properly. There is no successful GitHub interaction without SSL. In addition it is stated that they also don't accept an empty User-Agent in the request header.

The correct (highly simplified) solution is the following:

require 'net/http'    

url = URI("https://api.github.com/rate_limit")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

req = Net::HTTP::Get.new(url)
req["Authorization"] = 'token <MY-40-CHAR-TOKEN>'
res = http.request(req)

puts res.read_body

Replacing the code in OP in the appropriate places fixes this.


For future reference, if you need to convert a curl into Ruby's net/http format, use this site:

  • curl-to-ruby.

Rails 3. How to add an API to a rails app

a good starting point might be reading up on REST and responders

Then to interact with the API from another rails app, you can use ActiveResource. There's a Railscast on it.

An example:

#API side
class ProductsController < ApplicationController
respond_to :json

def index
@products = Product.all
respond_with(@products)
end
end

#Client
# models/product.rb
class Product < ActiveResource::Base
self.site = "http://your-api-app.com"
end

Cannot connect to Github account using octokit

I had the same problem.
I solved problem just like this:

client.user(ENV['GITHUB_LOGIN'], :headers => { "X-GitHub-OTP" => "2fa-token"})

If you don't have an ENV['GITHUB_LOGIN'], just type Github username

client.user('codescaptain', :headers => { "X-GitHub-OTP" => "2fa-token"})


Related Topics



Leave a reply



Submit