Skip to content

Commit

Permalink
Merge pull request #5 from DeweyLabs/isolated-execution
Browse files Browse the repository at this point in the history
Converting client to configuration by instance
  • Loading branch information
ScotterC authored May 21, 2024
2 parents b8d06ee + 638e1d1 commit 8597610
Show file tree
Hide file tree
Showing 16 changed files with 442 additions and 163 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,13 @@ require 'wp_api_client'
```ruby
# create a client

WpApiClient.configure do |api_client|
wordpress_instance = WpApiClient::Instance.new

wordpress_instance.configure do |api_client|
api_client.endpoint = 'http://example.com/wp-json/wp/v2'
end

@api = WpApiClient.get_client
@api = wordpress_instance.client

# get some posts
posts = @api.get('custom_post_type/') # or "posts/" etc
Expand Down Expand Up @@ -171,7 +173,7 @@ queen = king.relations("http://api.myuniqueuri.com/marriage").first
The solution is to register the relationship on configuration:

```ruby
WpApiClient.configure do |c|
wordpress_instance.configure do |c|
c.define_mapping("http://api.myuniqueuri.com/marriage", :post)
end

Expand Down Expand Up @@ -199,23 +201,23 @@ posts = term.posts
Provide a symbol-keyed hash of `token`, `token_secret`, `consumer_key` and `consumer_secret` on configuration.

```ruby
WpApiClient.configure do |api_client|
wordpress_instance.configure do |api_client|
api_client.oauth_credentials = oauth_credentials_hash
end

client = WpApiClient.get_client
client = wordpress_instance.client
```

#### Basic Auth

Provide a symbol-keyed hash of `username` and `password` on configuration.

```ruby
WpApiClient.configure do |api_client|
wordpress_instance.configure do |api_client|
api_client.basic_auth = {username: 'miles', password: 'smile'}
end

client = WpApiClient.get_client
client = wordpress_instance.client
```

## Concurrency
Expand Down
12 changes: 1 addition & 11 deletions lib/wp_api_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,9 @@
require "wp_api_client/relationship"

module WpApiClient

def self.get_client
@client ||= Client.new(Connection.new(configuration))
end

# for tests
def self.reset!
@client = nil
end

class RelationNotDefined < StandardError; end
class ErrorResponse < StandardError

class ErrorResponse < StandardError
attr_reader :error
attr_reader :status

Expand Down
36 changes: 29 additions & 7 deletions lib/wp_api_client/client.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
module WpApiClient
class Client
attr_reader :connection, :client_instance

def initialize(connection)
def initialize(connection, client_instance)
@connection = connection
@client_instance = client_instance
end

def get(url, params = {})
Expand All @@ -16,27 +18,47 @@ def get(url, params = {})
end

def concurrently
@concurrent_client ||= ConcurrentClient.new(@connection)
@concurrent_client ||= ConcurrentClient.new(@connection, client_instance)
yield @concurrent_client
result = @concurrent_client.run
@concurrent_client = nil
result
end

private
def configuration
client_instance.configuration
end

private

def api_path_from(url)
url.split('wp/v2/').last
url.split("wp/v2/").last
end

# Take the API response and figure out what it is
#  Take the API response and figure out what it is
def native_representation_of(response_body)
# Do we have a collection of objects?
if response_body.is_a? Array
WpApiClient::Collection.new(response_body, @headers)
WpApiClient::Collection.new(response_body, @headers, client_instance)
else
WpApiClient::Entities::Base.build(response_body)
WpApiClient::Entities::Base.build(response_body, client_instance)
end
end
end

class Instance
attr_reader :configuration

def initialize
@configuration = Configuration.new
end

def configure
yield(@configuration)
end

def client
@client ||= Client.new(Connection.new(@configuration), self)
end
end
end
30 changes: 15 additions & 15 deletions lib/wp_api_client/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ class Collection

attr_accessor :resources, :total_available

def initialize(resources, headers = nil)
def initialize(resources, headers = nil, client_instance)
resources = [resources] unless resources.is_a? Array
@resources = resources.map { |object| WpApiClient::Entities::Base.build(object) }
@resources = resources.map { |object| WpApiClient::Entities::Base.build(object, client_instance) }
if headers
@links = parse_link_header(headers['Link'])
@total_available = headers['X-WP-TOTAL'].to_i
@links = parse_link_header(headers["Link"])
@total_available = headers["X-WP-TOTAL"].to_i
end
end

def each(&block)
@resources.each{|p| block.call(p)}
@resources.each { |p| block.call(p) }
end

def next_page
Expand All @@ -25,24 +25,24 @@ def previous_page
@links[:prev] && @links[:prev]
end

def method_missing(method, *args)
@resources.send(method, *args)
def method_missing(method, *)
@resources.send(method, *)
end

private
private

# https://www.snip2code.com/Snippet/71914/Parse-link-headers-from-Github-API-in-Ru
def parse_link_header(header, params={})
links = Hash.new
def parse_link_header(header, params = {})
links = {}
return links unless header
parts = header.split(',')
parts = header.split(",")
parts.each do |part, index|
section = part.split(';')
url = section[0][/<(.*)>/,1]
name = section[1][/rel="(.*)"/,1].to_sym
section = part.split(";")
url = section[0][/<(.*)>/, 1]
name = section[1][/rel="(.*)"/, 1].to_sym
links[name] = url
end
return links
links
end
end
end
12 changes: 8 additions & 4 deletions lib/wp_api_client/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,14 @@ def initialize
end

def basic_auth=(hash)
# Symbolizes one level of keys
@basic_auth = hash.each_with_object({}) do |(key, value), result|
symbol_key = key.to_sym
result[symbol_key] = value
@basic_auth = if hash.nil?
nil
else
# Symbolizes one level of keys
hash.each_with_object({}) do |(key, value), result|
symbol_key = key.to_sym
result[symbol_key] = value
end
end
end

Expand Down
21 changes: 11 additions & 10 deletions lib/wp_api_client/entities/base.rb
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
require 'open-uri'
require 'ostruct'
require "open-uri"
require "ostruct"

module WpApiClient
module Entities
class Base
attr_reader :resource
attr_reader :resource, :client_instance

def self.build(resource)
def self.build(resource, client_instance)
raise Exception if resource.nil?
type = WpApiClient::Entities::Types.find { |type| type.represents?(resource) }
type.new(resource)
type.new(resource, client_instance)
end

def initialize(resource)
def initialize(resource, client_instance)
unless resource.is_a? Hash or resource.is_a? OpenStruct
raise ArgumentError.new('Tried to initialize a WP-API resource with something other than a Hash')
raise ArgumentError.new("Tried to initialize a WP-API resource with something other than a Hash")
end
@resource = OpenStruct.new(resource)
@client_instance = client_instance
end

def links
Expand All @@ -25,16 +26,16 @@ def links

def relations(relation, relation_to_return = nil)
relationship = Relationship.new(@resource, relation)
relations = relationship.get_relations
relations = relationship.get_relations(client_instance)
if relation_to_return
relations[relation_to_return]
else
relations
end
end

def method_missing(method, *args)
@resource.send(method, *args)
def method_missing(method, *)
@resource.send(method, *)
end
end
end
Expand Down
5 changes: 2 additions & 3 deletions lib/wp_api_client/entities/term.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
module WpApiClient
module Entities
class Term < Base
alias :term :resource
alias_method :term, :resource

def self.represents?(json)
json.dig("_links", "about") and json["_links"]["about"].first["href"] =~ /wp\/v2\/taxonomies/
end

def taxonomy
WpApiClient.get_client.get(links["about"].first["href"])
client_instance.client.get(links["about"].first["href"])
end

def posts(post_type = nil)
relations("http://api.w.org/v2/post_type", post_type)
end

end
end
end
Loading

0 comments on commit 8597610

Please sign in to comment.