Skip to content

Instantly share code, notes, and snippets.

@xiangzhuyuan
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiangzhuyuan/c53defbd4a6da97f48e2 to your computer and use it in GitHub Desktop.
Save xiangzhuyuan/c53defbd4a6da97f48e2 to your computer and use it in GitHub Desktop.
学习 active resource ActiveSupport::JSON.decode(json)
def find(*arguments)
scope = arguments.slice!(0)
options = arguments.slice!(0) || {}
case scope
when :all then find_every(options)
when :first then find_every(options).first
when :last then find_every(options).last
when :one then find_one(options)
else find_single(scope, options)
end
end
# Find a single resource from a one-off URL
def find_one(options)
case from = options[:from]
when Symbol
instantiate_record(get(from, options[:params]))
when String
path = "#{from}#{query_string(options[:params])}"
instantiate_record(format.decode(connection.get(path, headers).body)) #关键
end
end
#1. connection.get(path, headers)
#2. format.decode(connection.get(path, headers).body)
#3. instantiate_record(format.decode(connection.get(path, headers).body))
#1.
# An instance of ActiveResource::Connection that is the base \connection to the remote service.
# The +refresh+ parameter toggles whether or not the \connection is refreshed at every request
# or not (defaults to <tt>false</tt>).
def connection(refresh = false)
if defined?(@connection) || superclass == Object
@connection = Connection.new(site, format) if refresh || @connection.nil?
@connection.proxy = proxy if proxy
@connection.user = user if user
@connection.password = password if password
@connection.auth_type = auth_type if auth_type
@connection.timeout = timeout if timeout
@connection.ssl_options = ssl_options if ssl_options
@connection
else
superclass.connection
end
end
#~/.rvm/gems/ruby-2.1.2/gems/activeresource-3.2.17/lib/active_resource/connection.rb
# Executes a GET request.
# Used to get (find) resources.
def get(path, headers = {})
with_auth { request(:get, path, build_request_headers(headers, :get, self.site.merge(path))) }
end
# .body 返回内容
#2. format.decode() ????what?
#~/.rvm/gems/ruby-2.1.2/gems/activeresource-3.2.17/lib/active_resource/formats/json_format.rb
require 'active_support/json'
module ActiveResource
module Formats
module JsonFormat
extend self
def extension
"json"
end
def mime_type
"application/json"
end
def encode(hash, options = nil)
ActiveSupport::JSON.encode(hash, options)
end
def decode(json)
Formats.remove_root(ActiveSupport::JSON.decode(json)) # 这他妈是关键
end
end
end
end
#3. ?
def instantiate_record(record, prefix_options = {})
new(record, true).tap do |resource|
resource.prefix_options = prefix_options
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment