repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/service/result/success.rb
lib/aldous/service/result/success.rb
require 'aldous/service/result/base' module Aldous class Service module Result class Success < ::Aldous::Service::Result::Base end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/service/result/base.rb
lib/aldous/service/result/base.rb
require 'aldous/simple_dto' require 'aldous/service/result/base/predicate_methods_for_inheritance' module Aldous class Service module Result class Base < ::Aldous::SimpleDto extend PredicateMethodsForInheritance end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/service/result/failure.rb
lib/aldous/service/result/failure.rb
require 'aldous/service/result/base' module Aldous class Service module Result class Failure < ::Aldous::Service::Result::Base end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/service/result/base/predicate_methods_for_inheritance.rb
lib/aldous/service/result/base/predicate_methods_for_inheritance.rb
require 'aldous/service/result/base' module Aldous class Service module Result class Base < ::Aldous::SimpleDto module PredicateMethodsForInheritance # For every child class, create a predicate method on the base named # after the child that returns false and override the same predicate # method on the child to return true. So if the child class is called # Failure then we'll have a predicate method called failure? which will # return false on the base class and true on the actual child class. def inherited(child) return if child.name == nil # unnamed class child_class_name_as_predicate = "#{underscore(child.name.split("::").last)}?" add_predicate_method_to_class(Aldous::Service::Result::Base, child_class_name_as_predicate, false) add_predicate_method_to_class(child, child_class_name_as_predicate, true) end private def add_predicate_method_to_class(klass, method_name, method_value) unless klass.instance_methods(false).include?(method_name) klass.class_eval do define_method method_name do method_value end end end end def underscore(string) string.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/errors/user_error.rb
lib/aldous/errors/user_error.rb
module Aldous module Errors class UserError < StandardError end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/view/blank/json_view.rb
lib/aldous/view/blank/json_view.rb
require 'aldous/respondable/renderable' module Aldous module View module Blank class JsonView < Respondable::Renderable def template { json: {} } end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/view/blank/html_view.rb
lib/aldous/view/blank/html_view.rb
require 'aldous/respondable/renderable' module Aldous module View module Blank class HtmlView < Respondable::Renderable def template { html: "", layout: true } end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/view/blank/atom_view.rb
lib/aldous/view/blank/atom_view.rb
require 'aldous/respondable/renderable' module Aldous module View module Blank class AtomView < Respondable::Renderable def template end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/send_data.rb
lib/aldous/respondable/send_data.rb
require 'aldous/respondable/base' module Aldous module Respondable class SendData < Base def action(controller) SendDataAction.new(data, options, controller, view_data) end def data raise Errors::UserError.new("SendData objects must define a 'data' method") end def options raise Errors::UserError.new("SendData objects must define an 'options' method") end private class SendDataAction attr_reader :controller, :view_data, :data, :options def initialize(data, options, controller, view_data) @controller = controller @view_data = view_data @data = data @options = options end def execute controller.send_data data, options end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/redirectable.rb
lib/aldous/respondable/redirectable.rb
require 'aldous/respondable/base' require 'aldous/respondable/shared/flash' module Aldous module Respondable class Redirectable < Base def action(controller) RedirectAction.new(location, controller, view_data, status) end def location raise Errors::UserError.new("Redirectable objects must define a 'location' method") end def default_status :found end private class RedirectAction attr_reader :controller, :view_data, :location, :status def initialize(location, controller, view_data, status) @location = location @controller = controller @view_data = view_data @status = status end def execute Shared::Flash.new(view_data, controller.flash).set_error controller.redirect_to location, {status: status} end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/headable.rb
lib/aldous/respondable/headable.rb
require 'aldous/respondable/base' module Aldous module Respondable class Headable < Base def action(controller) HeadAction.new(controller, status) end def default_status :ok end private class HeadAction attr_reader :controller, :status def initialize(controller, status) @controller = controller @status = status end def execute controller.head status end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/renderable.rb
lib/aldous/respondable/renderable.rb
require 'aldous/respondable/base' require 'aldous/respondable/shared/flash' module Aldous module Respondable class Renderable < Base def action(controller) RenderAction.new(template, status, controller, view_data) end def default_status :ok end def default_template_locals {} end def template_data {} end def template(extra_locals = {}) template_locals = template_data[:locals] || {} locals = default_template_locals.merge(template_locals) locals = locals.merge(extra_locals || {}) template_hash = template_data.merge(locals: locals) template_hash end private class RenderAction attr_reader :template, :controller, :view_data, :status def initialize(template, status, controller, view_data) @status = status @template = template @controller = controller @view_data = view_data end def execute Shared::Flash.new(view_data, controller.flash.now).set_error controller.render template.merge(status: status) end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/base.rb
lib/aldous/respondable/base.rb
require 'aldous/view_builder' require 'aldous/simple_dto' module Aldous module Respondable class Base attr_reader :view_data, :view_context def initialize(status, view_data, view_context, view_builder = nil) @status = status @view_data = view_data @view_context = view_context @view_builder = view_builder end def action(controller) raise Errors::UserError.new("Respondables must define an 'action' method") end def status @status || default_status end def default_status :ok end def view_builder @view_builder ||= ViewBuilder.new(view_context, view_data._data) end ################################################ # NOTE deprecated ################################################ def build_view(respondable_class, extra_data = {}) # deprecated view_builder.build(respondable_class, extra_data) end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/request_http_basic_authentication.rb
lib/aldous/respondable/request_http_basic_authentication.rb
module Aldous module Respondable class RequestHttpBasicAuthentication < Base def action(controller) RequestHttpBasicAuthenticationAction.new(controller) end private class RequestHttpBasicAuthenticationAction attr_reader :controller def initialize(controller) @controller = controller end def execute controller.request_http_basic_authentication end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
envato-archive/aldous
https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/lib/aldous/respondable/shared/flash.rb
lib/aldous/respondable/shared/flash.rb
module Aldous module Respondable module Shared class Flash attr_reader :result, :flash_container def initialize(result, flash_container) @result = result @flash_container = flash_container end def set_error flash_container[:error] = error if error end private def error result.errors.first end end end end end
ruby
MIT
0eb0a18b511345ad5fea3072a7111ea5ebcfb30d
2026-01-04T17:54:58.048556Z
false
rweng/underscore-rails
https://github.com/rweng/underscore-rails/blob/5267dba35174120b096d36e5941a8e49b5c921a2/lib/underscore-rails.rb
lib/underscore-rails.rb
require "underscore-rails/version" module Underscore module Rails if defined?(::Rails) and Gem::Requirement.new('>= 3.1').satisfied_by?(Gem::Version.new ::Rails.version) class Rails::Engine < ::Rails::Engine # this class enables the asset pipeline end end end end
ruby
MIT
5267dba35174120b096d36e5941a8e49b5c921a2
2026-01-04T17:55:02.820262Z
false
rweng/underscore-rails
https://github.com/rweng/underscore-rails/blob/5267dba35174120b096d36e5941a8e49b5c921a2/lib/underscore-rails/version.rb
lib/underscore-rails/version.rb
module Underscore module Rails VERSION = "1.8.3" end end
ruby
MIT
5267dba35174120b096d36e5941a8e49b5c921a2
2026-01-04T17:55:02.820262Z
false
basecamp/fast_remote_cache
https://github.com/basecamp/fast_remote_cache/blob/6dc16b790ad3e5cc20b11e429f69b12e24e53cd1/init.rb
init.rb
# Include hook code here
ruby
MIT
6dc16b790ad3e5cc20b11e429f69b12e24e53cd1
2026-01-04T17:55:03.194780Z
false
basecamp/fast_remote_cache
https://github.com/basecamp/fast_remote_cache/blob/6dc16b790ad3e5cc20b11e429f69b12e24e53cd1/recipes/fast_remote_cache.rb
recipes/fast_remote_cache.rb
# --------------------------------------------------------------------------- # This is a recipe definition file for Capistrano. The tasks are documented # below. # --------------------------------------------------------------------------- # This file is distributed under the terms of the MIT license by 37signals, # LLC, and is copyright (c) 2008 by the same. See the LICENSE file distributed # with this file for the complete text of the license. # --------------------------------------------------------------------------- $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) namespace :fast_remote_cache do desc <<-DESC Perform any setup required by fast_remote_cache. This is called automatically after deploy:setup, but may be invoked manually to configure a new machine. It is also necessary to invoke when you are switching to the fast_remote_cache strategy for the first time. DESC task :setup, :except => { :no_release => true } do if deploy_via == :fast_remote_cache strategy.setup! else logger.important "you're including the fast_remote_cache strategy, but not using it!" end end desc <<-DESC Updates the remote cache. This is handy for either priming a new box so the cache is all set for the first deploy, or for preparing for a large deploy by making sure the cache is updated before the deploy goes through. Either way, this will happen automatically as part of a deploy; this task is purely convenience for giving admins more control over the deployment. DESC task :prepare, :except => { :no_release => true } do if deploy_via == :fast_remote_cache strategy.prepare! else logger.important "#{current_task.fully_qualified_name} only works with the fast_remote_cache strategy" end end end after "deploy:setup", "fast_remote_cache:setup"
ruby
MIT
6dc16b790ad3e5cc20b11e429f69b12e24e53cd1
2026-01-04T17:55:03.194780Z
false
basecamp/fast_remote_cache
https://github.com/basecamp/fast_remote_cache/blob/6dc16b790ad3e5cc20b11e429f69b12e24e53cd1/lib/capistrano/recipes/deploy/strategy/fast_remote_cache.rb
lib/capistrano/recipes/deploy/strategy/fast_remote_cache.rb
# --------------------------------------------------------------------------- # This implements a specialization of the standard Capistrano RemoteCache # deployment strategy. The most significant difference between this strategy # and the RemoteCache is the way the cache is copied to the final release # directory: it uses the bundled "copy.rb" script to use hard links to the # files instead of actually copying, so the copy stage is much, much faster. # --------------------------------------------------------------------------- # This file is distributed under the terms of the MIT license by 37signals, # LLC, and is copyright (c) 2008 by the same. See the LICENSE file distributed # with this file for the complete text of the license. # --------------------------------------------------------------------------- require 'capistrano/recipes/deploy/strategy/remote_cache' class Capistrano::Deploy::Strategy::FastRemoteCache < Capistrano::Deploy::Strategy::RemoteCache def check! super.check do |d| d.remote.command(configuration.fetch(:ruby, "ruby")) d.remote.directory(bin_path) d.remote.file(File.join(bin_path, "copy.rb")) end end def setup! run "mkdir -p #{bin_path}" upload(File.join(File.dirname(__FILE__), "utilities", "copy.rb"), File.join(bin_path, "copy.rb")) end def prepare! update_repository_cache end private def bin_path @bin_path ||= File.join(configuration[:shared_path], "bin") end def copy_repository_cache logger.trace "copying the cached version to #{configuration[:release_path]}" ruby = configuration.fetch(:ruby, "ruby") excludes = Array(configuration[:copy_exclude]).join(" ") run "#{ruby} #{File.join(bin_path, 'copy.rb')} #{repository_cache} #{configuration[:release_path]} #{excludes} && #{mark}" end end
ruby
MIT
6dc16b790ad3e5cc20b11e429f69b12e24e53cd1
2026-01-04T17:55:03.194780Z
false
basecamp/fast_remote_cache
https://github.com/basecamp/fast_remote_cache/blob/6dc16b790ad3e5cc20b11e429f69b12e24e53cd1/lib/capistrano/recipes/deploy/strategy/utilities/copy.rb
lib/capistrano/recipes/deploy/strategy/utilities/copy.rb
# --------------------------------------------------------------------------- # A simple copy script for doing hard links and symbolic links instead of # explicit copies. Some OS's will already have a utility to do this, but # some won't; this file suffices in either case. # # Usage: ruby copy.rb <source> <target> <exclude> ... # # The <source> directory is recursively descended, and hard links to all of # the files are created in corresponding locations under <target>. Symbolic # links in <source> map to symbolic links in <target> that point to the same # destination. # # All arguments after <target> are taken to be exclude patterns. Any file # or directory in <source> that matches any of those patterns will be # skipped, and will thus not be present in <target>. # --------------------------------------------------------------------------- # This file is distributed under the terms of the MIT license by 37signals, # LLC, and is copyright (c) 2008 by the same. See the LICENSE file distributed # with this file for the complete text of the license. # --------------------------------------------------------------------------- require 'fileutils' from = ARGV.shift or abort "need source directory" to = ARGV.shift or abort "need target directory" exclude = ARGV from = File.expand_path(from) to = File.expand_path(to) Dir.chdir(from) do FileUtils.mkdir_p(to) queue = Dir.glob("*", File::FNM_DOTMATCH) while queue.any? item = queue.shift name = File.basename(item) next if name == "." || name == ".." next if exclude.any? { |pattern| File.fnmatch(pattern, item) } source = File.join(from, item) target = File.join(to, item) if File.symlink?(item) FileUtils.ln_s(File.readlink(source), target) elsif File.directory?(item) queue += Dir.glob("#{item}/*", File::FNM_DOTMATCH) FileUtils.mkdir_p(target, :mode => File.stat(item).mode) else FileUtils.ln(source, target) end end end
ruby
MIT
6dc16b790ad3e5cc20b11e429f69b12e24e53cd1
2026-01-04T17:55:03.194780Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require 'rspec/its' require 'faker' require 'webmock/rspec' # require 'byebug' require 'saharspec' require 'simplecov' require 'coveralls' Coveralls.wear! SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new( [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter] ) $LOAD_PATH.unshift 'lib' require 'tlaw' RSpec.configure do |config| config.disable_monkey_patching! config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end end RSpec::Matchers.define :get_webmock do |url| match do |block| WebMock.reset! stub_request(:get, url).tap { |req| req.to_return(@response) if @response } block.call expect(WebMock).to have_requested(:get, url) end chain :and_return do |response| @response = case response when String {body: response} when Hash response else fail "Expected string or Hash of params, got #{response.inspect}" end end supports_block_expectations end class String # allows to pretty test agains multiline strings: # %Q{ # |test # |me # }.unindent # => # "test # me" def unindent gsub(/\n\s+?\|/, "\n") # for all lines looking like "<spaces>|" -- remove this. .gsub(/\|\n/, "\n") # allow to write trailing space not removed by editor .gsub(/\A\n|\n\s+\Z/, '') # remove empty strings before and after end end class TLAW::Util::Description # rubocop:disable Style/ClassAndModuleChildren # to make it easily comparable with strings expected. def inspect to_s.inspect end end RSpec::Matchers.define :not_have_key do |key| match do |actual| expect(actual).not_to be_key(key) end end RSpec::Matchers.define :define_constant do |name| match do |block| if const_exists?(name) @already_exists = true break false end block.call const_exists?(name) end description do "expected block to create constant #{name}" end failure_message do if @already_exists "#{description}, but it is already existing" else last_found = @path[0...@modules.count - 1].join('::') not_found = @path[@modules.count - 1] # FIXME: slice or something, I forgot :( problem = @modules.last.respond_to?(:const_defined?) ? "does not define #{not_found}" : 'is not a module' "#{description}, but #{last_found} #{problem}" end end supports_block_expectations def const_exists?(name) @path = name.split('::').drop_while(&:empty?) @modules = @path.reduce([Kernel]) { |(*prevs, cur), nm| break [*prevs, cur] unless cur.respond_to?(:const_defined?) && cur.const_defined?(nm) [*prevs, cur, cur.const_get(nm)] } @modules.count - 1 == @path.size end end def param(name, **arg) TLAW::Param.new(name: name, **arg) end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/endpoint_spec.rb
spec/tlaw/endpoint_spec.rb
# frozen_string_literal: true RSpec.describe TLAW::Endpoint do let(:parent_class) { class_double('TLAW::ApiPath', url_template: 'http://example.com/{x}', full_param_defs: [param(:x), param(:y)]) } let(:param_defs) { [param(:a), param(:b)] } let(:cls) { described_class .define(symbol: :ep, path: path, param_defs: param_defs) .tap { |cls| cls.parent = parent_class } } let(:path) { '/foo' } describe 'class behavior' do describe 'formatting' do subject { cls } before { allow(cls).to receive(:name).and_return('Endpoint') } its(:inspect) { is_expected.to eq 'Endpoint(call-sequence: ep(a: nil, b: nil); docs: .describe)' } its(:describe) { is_expected.to be_a String } end end describe 'object behavior' do let(:parent) { instance_double( 'TLAW::ApiPath', prepared_params: parent_params, api: api, parent: nil ) } let(:api) { instance_double('TLAW::API', request: nil) } let(:parent_params) { {x: 'bar', y: 'baz'} } subject(:endpoint) { cls.new(parent, a: 1, b: 2) } its(:request_params) { are_expected.to eq(y: 'baz', a: '1', b: '2') } its(:parents) { are_expected.to eq [parent] } describe '#url' do its(:url) { is_expected.to eq 'http://example.com/bar/foo' } context 'with .. in template' do let(:path) { '/../foo' } its(:url) { is_expected.to eq 'http://example.com/foo' } end end describe 'formatting' do before { allow(cls).to receive(:name).and_return('Endpoint') } its(:inspect) { is_expected.to eq '#<Endpoint(a: 1, b: 2); docs: .describe>' } its(:describe) { is_expected.to eq cls.describe } end describe '#call' do subject { endpoint.method(:call) } its_call { is_expected .to send_message(api, :request) .with('http://example.com/bar/foo', y: 'baz', a: '1', b: '2') .returning(instance_double('Faraday::Response', body: '')) } describe 'response parsing' do let(:cls) { TLAW::DSL::EndpointBuilder.new(symbol: :foo, **opts) .tap { |b| b.instance_eval(&definitions) } .finalize .tap { |cls| cls.parent = parent_class } } let(:endpoint) { cls.new(parent) } let(:opts) { {} } let(:definitions) { proc {} } let(:body) { { meta: {page: 1, per: 50}, rows: [{a: 1, b: 2}, {a: 3, b: 4}] }.to_json } before { allow(api) .to receive(:request) .and_return(instance_double('Faraday::Response', body: body)) } subject { endpoint.call } context 'by default' do it { is_expected.to eq( 'meta.page' => 1, 'meta.per' => 50, 'rows' => TLAW::DataTable.new([{a: 1, b: 2}, {a: 3, b: 4}]) ) } end context 'with XML response' do let(:opts) { {xml: true} } let(:body) { '<foo><bar>1</bar><baz>2</baz></foo>' } it { is_expected.to eq('foo.bar' => '1', 'foo.baz' => '2') } end context 'additional processors' do let(:definitions) { proc do post_process { |h| h['additional'] = 5 } post_process('meta.per') { |p| p**2 } post_process_items('rows') { post_process { |i| i['c'] = -i['a'] } post_process('a', &:to_s) } end } it { is_expected.to eq( 'meta.page' => 1, 'meta.per' => 2500, 'additional' => 5, 'rows' => TLAW::DataTable.new([ {'a' => '1', 'b' => 2, 'c' => -1}, {'a' => '3', 'b' => 4, 'c' => -3} ]) ) } end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/api_path_spec.rb
spec/tlaw/api_path_spec.rb
# frozen_string_literal: true RSpec.describe TLAW::APIPath do let(:parent_cls) { class_double( 'TLAW::ApiPath', parent: nil, url_template: 'http://example.com/{x}', full_param_defs: [param(:x), param(:y)] ) } let(:parent) { instance_double('TLAW::APIPath', prepared_params: {x: 'xxx'}) } let(:cls) { described_class.define( symbol: :bar, path: '/bar', param_defs: [ param(:a, required: true), param(:b, type: Integer, field: :bb), param(:c, format: ->(t) { t.strftime('%Y-%m-%d') }), param(:d, type: {true => 't', false => 'f'}) ] ).tap { |res| res.parent = parent_cls } } describe '.define' do subject(:cls) { described_class.define(**args) } let(:args) { { symbol: :foo, path: '/bar', description: 'Test.', docs_link: 'http://google.com', param_defs: [ param(:a), param(:b, keyword: false, required: true) ] } } it { is_expected.to be_a(Class).and be.<(described_class) } # its(:definition) { is_expected.to eq args } it { is_expected.to have_attributes( symbol: :foo, path: '/bar', # description: 'Test.', -- hm... docs_link: 'http://google.com', param_defs: be_an(Array).and(have_attributes(size: 2)) ) } context 'without parent' do it { expect { cls.url_template } .to raise_error RuntimeError, "Orphan path /bar, can't determine full URL" } end context 'with parent' do before { cls.parent = parent_cls } it { is_expected.to have_attributes( url_template: 'http://example.com/{x}/bar', full_param_defs: be_an(Array).and(have_attributes(size: 4)) ) } its(:parents) { are_expected.to eq [parent_cls] } end end describe '#initialize' do subject(:path) { cls.new(parent, a: 5) } its(:parent) { is_expected.to eq parent } end describe '#prepared_params' do subject { ->(params) { cls.new(parent, **params).prepared_params } } its_call(a: 1, b: 2, c: Time.parse('2017-05-01'), d: true) { is_expected.to ret(a: '1', bb: '2', c: '2017-05-01', d: 't', x: 'xxx') } its_call(a: 1, b: nil) { is_expected.to ret(a: '1', x: 'xxx') } its_call(a: [1, 2, 3]) { is_expected.to ret(a: '1,2,3', x: 'xxx') } its_call(b: 2) { is_expected.to raise_error(ArgumentError, 'Missing arguments: a') } its_call(a: 1, e: 2) { is_expected.to raise_error(ArgumentError, 'Unknown arguments: e') } its_call(a: 1, b: 'test') { is_expected.to raise_error(TypeError, 'b: expected instance of Integer, got "test"') } end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/param_spec.rb
spec/tlaw/param_spec.rb
# frozen_string_literal: true require 'tlaw/param' RSpec.describe TLAW::Param do describe '#initialize' do subject { described_class.new(**args) } context 'with minimal args' do let(:args) { {name: :x} } it { is_expected.to have_attributes( name: :x, field: :x, required?: false, keyword?: true, description: nil, default: nil ) } end context 'with all the args' do let(:args) { { name: :x, field: :_xx, required: true, keyword: false, description: 'Desc.', default: 5, # we don't check which value it gives, just that constructor don't fail format: :to_s.to_proc } } it { is_expected.to have_attributes( name: :x, field: :_xx, required?: true, keyword?: false, description: 'Desc.', default: 5 ) } end end describe '#call' do subject { ->(value, **definition) { described_class.new(**defaults, **definition).call(value) } } let(:defaults) { {name: :x} } context 'basics' do its_call('foo') { is_expected.to ret(x: 'foo') } its_call(5) { is_expected.to ret(x: '5') } its_call('foo', field: :bar) { is_expected.to ret(bar: 'foo') } end context 'typechecking' do its_call(5, type: Integer) { is_expected.to ret(x: '5') } its_call('5', type: Integer) { is_expected.to raise_error TypeError, 'x: expected instance of Integer, got "5"' } its_call(Time.parse('2018-03-01'), type: :year) { is_expected.to ret(x: '2018') } its_call('2018-03-01', type: :year) { is_expected.to raise_error TypeError, 'x: expected object responding to #year, got "2018-03-01"' } end context 'enum conversion' do its_call(true, type: {true => 'gzip', false => nil}) { is_expected.to ret(x: 'gzip') } end context 'value formatting' do its_call(5, format: ->(x) { -x }) { is_expected.to ret(x: '-5') } end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/api_spec.rb
spec/tlaw/api_spec.rb
# frozen_string_literal: true RSpec.describe TLAW::API do let(:cls) { Class.new(described_class).tap { |cls| cls.setup(base_url: 'http://foo/{bar}') } } describe '.define' do subject(:cls) { Class.new(described_class) } before { cls.define do base 'http://foo/bar' endpoint :a namespace :b end } its(:url_template) { is_expected.to eq 'http://foo/bar' } its(:endpoints) { is_expected.to contain_exactly(be.<(TLAW::Endpoint).and(have_attributes(symbol: :a))) } its(:namespaces) { is_expected.to contain_exactly(be.<(TLAW::Namespace).and(have_attributes(symbol: :b))) } end describe '.setup' do context 'with keywords' do subject(:cls) { Class.new(described_class) } before { cls.setup(base_url: 'http://foo/{bar}', param_defs: [param(:x)]) allow(cls).to receive(:name).and_return('MyAPI') } it { is_expected.to have_attributes( url_template: 'http://foo/{bar}', symbol: nil, path: '' ) } its(:inspect) { is_expected.to eq 'MyAPI(call-sequence: MyAPI.new(x: nil); docs: .describe)' } end end describe '#initialize' do it { expect { |b| cls.new(&b) }.to yield_with_args(instance_of(Faraday::Connection)) } end describe '#request' do let(:api) { cls.new } subject { api.request('http://foo/bar?x=1', y: 2) } its_block { is_expected.to get_webmock('http://foo/bar?x=1&y=2').and_return('{}') } context 'on error' do before { stub_request(:get, /.*/).to_return(status: 404, body: 'unparseable error') } its_block { is_expected.to raise_error TLAW::API::Error, 'HTTP 404 at http://foo/bar?x=1&y=2: unparseable error' } end context 'on error with extractable message' do before { stub_request(:get, /.*/).to_return(status: 404, body: {error: 'SNAFU'}.to_json) } its_block { is_expected.to raise_error TLAW::API::Error, 'HTTP 404 at http://foo/bar?x=1&y=2: SNAFU' } end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/response_processors_spec.rb
spec/tlaw/response_processors_spec.rb
# frozen_string_literal: true RSpec.describe TLAW::ResponseProcessors do # TODO: more thorough tests, these are obviously ad-hoc describe 'Generators.transform_nested' do context 'without nested key' do subject { described_class::Generators.transform_nested(:c) { |h| h[:d] = 5 } } its_call(a: 1, b: 2, c: [{a: 3}, {b: 4}]) { is_expected.to ret(a: 1, b: 2, c: [{a: 3, d: 5}, {b: 4, d: 5}]) } end context 'with nested key' do subject { described_class::Generators.transform_nested(:c, :a, &:to_s) } its_call(a: 1, b: 2, c: [{a: 3}, {b: 4}]) { is_expected.to ret(a: 1, b: 2, c: [{a: '3'}, {b: 4}]) } end end describe '.flatten' do let(:source) { { 'response' => { 'count' => 10 }, 'list' => [ {'weather' => {'temp' => 10}}, {'weather' => {'temp' => 15}} ] } } subject { described_class.flatten(source) } it { is_expected.to eq( 'response.count' => 10, 'list' => [ {'weather.temp' => 10}, {'weather.temp' => 15} ] ) } end describe '.datablize' do let(:source) { { 'count' => 2, 'list' => [ {'i' => 1, 'val' => 'xxx'}, {'i' => 2, 'val' => 'yyy'} ] } } subject { described_class.datablize(source)['list'] } it { is_expected.to be_a TLAW::DataTable } its(:keys) { are_expected.to eq %w[i val] } end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/data_table_spec.rb
spec/tlaw/data_table_spec.rb
# frozen_string_literal: true module TLAW RSpec.describe DataTable do let(:data) { [ {a: 1, b: 'a', c: Date.parse('2016-01-01')}, {a: 2, b: 'b', c: Date.parse('2016-02-01'), d: 'dummy'}, {a: 3, b: 'c', c: Date.parse('2016-03-01')} ] } subject(:table) { described_class.new(data) } context '#==' do it { is_expected.to eq described_class.new(data) } end context 'Array-ish behavior' do its(:size) { is_expected.to eq 3 } its([0]) { is_expected.to eq('a' => 1, 'b' => 'a', 'c' => Date.parse('2016-01-01'), 'd' => nil) } its(:to_a) { is_expected.to eq([ {'a' => 1, 'b' => 'a', 'c' => Date.parse('2016-01-01'), 'd' => nil}, {'a' => 2, 'b' => 'b', 'c' => Date.parse('2016-02-01'), 'd' => 'dummy'}, {'a' => 3, 'b' => 'c', 'c' => Date.parse('2016-03-01'), 'd' => nil} ]) } context 'Enumerable' end context 'Hash-ish behavior' do its(:keys) { is_expected.to eq %w[a b c d] } its([:a]) { is_expected.to eq [1, 2, 3] } its(['a']) { is_expected.to eq [1, 2, 3] } its(:to_h) { is_expected.to eq( 'a' => [1, 2, 3], 'b' => %w[a b c], 'c' => [Date.parse('2016-01-01'), Date.parse('2016-02-01'), Date.parse('2016-03-01')], 'd' => [nil, 'dummy', nil] ) } context '#columns(a, b)' do subject { table.columns(:a, :b) } it { is_expected.to eq described_class.new( [ {a: 1, b: 'a'}, {a: 2, b: 'b'}, {a: 3, b: 'c'} ] ) } end end context '#inspect' do its(:inspect) { is_expected.to eq '#<TLAW::DataTable[a, b, c, d] x 3>' } end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/namespace_spec.rb
spec/tlaw/namespace_spec.rb
# frozen_string_literal: true RSpec.describe TLAW::Namespace do let(:cls) { described_class.define( symbol: :ns, path: '/ns', children: [ep, ns] ).tap { |c| c.parent = parent_cls } } let(:parent_cls) { class_double('TLAW::APIPath', url_template: 'http://foo/bar') } let(:ns) { described_class.define(symbol: :ns1, path: '/ns1', param_defs: [param(:x)]) } let(:ep) { TLAW::Endpoint.define(symbol: :ep1, path: '/ep1', param_defs: [param(:x)]) } describe '.define' do subject(:cls) { described_class.define( symbol: :ns, path: '/ns', param_defs: [param(:a), param(:b)], children: [ TLAW::Endpoint.define(symbol: :ep1, path: '/ep1'), described_class.define(symbol: :ns1, path: '/ns1') ] ) } its(:children) { are_expected .to match [ be.<(TLAW::Endpoint).and(have_attributes(symbol: :ep1, parent: cls)), be.<(described_class).and(have_attributes(symbol: :ns1, parent: cls)) ] } before { allow(cls).to receive(:name).and_return('Namespace') } its(:inspect) { is_expected.to eq 'Namespace(call-sequence: ns(a: nil, b: nil); namespaces: ns1; endpoints: ep1; docs: .describe)' } its(:describe) { is_expected.to be_a String } end describe '.child' do subject { cls.method(:child) } its_call(:ep1, restrict_to: TLAW::Endpoint) { is_expected.to ret be < TLAW::Endpoint } its_call(:ep1, restrict_to: described_class) { is_expected.to raise_error ArgumentError, 'Unregistered namespace: ep1' } its_call(:ns1, restrict_to: described_class) { is_expected.to ret be < described_class } its_call(:ns1) { is_expected.to ret be < described_class } its_call(:ns2) { is_expected.to raise_error ArgumentError, 'Unregistered path: ns2' } end describe '.endpoint' do subject { cls.method(:endpoint) } its_call(:ep1) { is_expected.to ret be < TLAW::Endpoint } its_call(:ns1) { is_expected.to raise_error ArgumentError, 'Unregistered endpoint: ns1' } its_call(:ns2) { is_expected.to raise_error ArgumentError, 'Unregistered endpoint: ns2' } end describe '.namespace' do subject { cls.method(:namespace) } its_call(:ns1) { is_expected.to ret be < described_class } its_call(:ep1) { is_expected.to raise_error ArgumentError, 'Unregistered namespace: ep1' } its_call(:ns2) { is_expected.to raise_error ArgumentError, 'Unregistered namespace: ns2' } end describe '.traverse' do let(:namespace_class) { TLAW::DSL::NamespaceBuilder.new(symbol: :root) do endpoint :endpoint namespace :child do endpoint :child_endpoint namespace :grand_child end end.finalize } subject { ->(*args) { namespace_class.traverse(*args).to_a } } it { is_expected.to ret contain_exactly( have_attributes(symbol: :endpoint), have_attributes(symbol: :child), have_attributes(symbol: :child_endpoint), have_attributes(symbol: :grand_child) ) } its_call(:endpoints) { is_expected.to ret contain_exactly( have_attributes(symbol: :endpoint), have_attributes(symbol: :child_endpoint) ) } its_call(:namespaces) { is_expected.to ret contain_exactly( have_attributes(symbol: :child), have_attributes(symbol: :grand_child) ) } its_call(:garbage) { is_expected.to raise_error KeyError } end describe '#child' do let(:obj) { cls.new(nil) } subject { obj.method(:child) } its_call(:ep1, TLAW::Endpoint, x: 1) { is_expected.to ret be_a(ep).and have_attributes(params: {x: 1}) } its_call(:ep1, described_class, x: 1) { is_expected.to raise_error ArgumentError, 'Unregistered namespace: ep1' } its_call(:ns1, described_class, x: 1) { is_expected.to ret be_a(ns).and have_attributes(params: {x: 1}) } end context 'formatting' do before { allow(cls).to receive(:name).and_return('Namespace') } subject(:obj) { cls.new(nil, a: 1, b: 5) } its(:inspect) { is_expected.to eq '#<Namespace(a: 1, b: 5); namespaces: ns1; endpoints: ep1; docs: .describe>' } its(:describe) { is_expected.to eq cls.describe } end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/dsl/namespace_builder_spec.rb
spec/tlaw/dsl/namespace_builder_spec.rb
# frozen_string_literal: true require 'tlaw/dsl/namespace_builder' RSpec.describe TLAW::DSL::NamespaceBuilder do let(:builder) { described_class.new(symbol: :foo) } describe '#endpoint' do subject { builder.endpoint(:foo, '/bar') { param :bar } } its_block { is_expected.to change(builder, :children) .to match( foo: have_attributes(symbol: :foo).and(be < TLAW::Endpoint) ) } its_block { is_expected .to send_message(TLAW::DSL::EndpointBuilder, :new) .with(symbol: :foo, path: '/bar', context: instance_of(described_class)).calling_original } end describe '#namespace' do subject { builder.namespace(:foo, '/bar') { param :bar } } its_block { is_expected .to change(builder, :children) .to match( foo: have_attributes(symbol: :foo).and(be < TLAW::Namespace) ) } its_block { is_expected .to send_message(described_class, :new) .with(symbol: :foo, path: '/bar', context: instance_of(described_class)).calling_original } context 'with string symbol' do subject { builder.namespace('foo') } its_block { is_expected.to change(builder, :children).to match(foo: have_attributes(symbol: :foo)) } end context 'when it is second definition' do before { builder.namespace(:foo, '/bar') { param :bar endpoint(:x) { param :y } } builder.namespace(:foo) { desc 'Description.' param :baz endpoint(:x) { param :y, required: true } } } subject { builder.children.values.first } it { is_expected .to be.<(TLAW::Namespace) .and have_attributes(symbol: :foo, path: '/bar', description: 'Description.') } its(:param_defs) { are_expected.to contain_exactly(have_attributes(name: :bar), have_attributes(name: :baz)) } its(:'endpoints.first.param_defs') { are_expected.to contain_exactly(have_attributes(name: :y, required?: true)) } end end describe '#finalize' do let(:builder) { described_class.new(symbol: :foo, path: '/bar/{baz}') do description 'Good description' param :foo, Integer param :quux endpoint :blah do param :nice end end } subject(:finalize) { builder.finalize } it { is_expected.to be < TLAW::Namespace } it { is_expected.to have_attributes( symbol: :foo, path: '/bar/{baz}', description: 'Good description', children: contain_exactly(be.<(TLAW::Endpoint)) ) } its(:instance_methods) { are_expected.to include(:blah) } end describe '#child_method_code' do subject { builder.send(:child_method_code, child) } context 'for endpoint' do let(:child) { TLAW::Endpoint.define(symbol: :blah, path: '', param_defs: [param(:nice)]) } it { is_expected.to eq <<~METHOD def blah(nice: nil) child(:blah, Endpoint, nice: nice).call end METHOD } end context 'for namespace' do let(:child) { TLAW::Namespace.define( symbol: :ns2, path: '', param_defs: [ param(:p1, required: true, keyword: false), param(:p2, required: true) ] ) } it { is_expected.to eq <<~METHOD def ns2(p1, p2:) child(:ns2, Namespace, p1: p1, p2: p2) end METHOD } end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/dsl/base_builder_spec.rb
spec/tlaw/dsl/base_builder_spec.rb
# frozen_string_literal: true require 'tlaw/dsl/base_builder' RSpec.describe TLAW::DSL::BaseBuilder do let(:opts) { {} } let(:builder) { described_class.new(symbol: :foo, **opts) } describe '#initialize' do subject(:call) { ->(*params) { described_class.new(*params).definition } } its_call(symbol: :foo) { is_expected.to ret include(symbol: :foo, path: '/foo') } its_call(symbol: :foo, path: '/bar') { is_expected.to ret include(symbol: :foo, path: '/bar') } context 'params auto-parsing' do subject { described_class.new(symbol: :foo, path: '/bar/{baz}?{quux}') } its(:params) { are_expected.to eq( baz: {keyword: false}, quux: {keyword: false} ) } end end describe '#description' do subject { builder.method(:description) } its_call("Very detailed and thoroughful\ndescription.") { is_expected.to change(builder, :definition).to include(description: "Very detailed and thoroughful\ndescription.") } its_call(%{ The description with some weird spacing. ...and other stuff. }) { is_expected.to change(builder, :definition).to include(description: "The description with some\nweird spacing.\n...and other stuff.") } end describe '#docs' do subject { builder.method(:docs) } its_call('https://google.com') { is_expected.to change(builder, :definition).to include(docs_link: 'https://google.com') } end describe '#param' do subject { builder.method(:param) } its_call(:x, Integer) { is_expected.to change(builder, :params).to include(x: {type: Integer}) } its_call(:x, desc: " Foo\n bar.") { is_expected.to change(builder, :params).to include(x: {description: "Foo\nbar."}) } its_call(:x, description: " Foo\n bar.") { is_expected.to change(builder, :params).to include(x: {description: "Foo\nbar."}) } context 'merging with params from path (preserve order and options)' do let(:opts) { {path: '/bar/{baz}'} } its_call(:baz, Integer) { is_expected.to change(builder, :params).to include(baz: {keyword: false, type: Integer}) } its_call(:x, Integer) { is_expected.to change { builder.params.keys }.to %i[baz x] } end end # TODO: params => param_defs test describe '#shared_def' do before { builder.shared_def(:foo) {} } subject { builder } its(:shared_definitions) { are_expected.to include(:foo) } end describe '#use_def' do before { builder.shared_def(:foo) { param :bar } } subject { builder.method(:use_def) } its_call(:foo) { is_expected.to change(builder, :params).to include(:bar) } its_call(:bar) { is_expected.to raise_error ArgumentError, ':bar is not a shared definition' } end describe '#post_process' describe '#post_process_items' end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/dsl/api_builder_spec.rb
spec/tlaw/dsl/api_builder_spec.rb
# frozen_string_literal: true require 'tlaw/dsl/api_builder' RSpec.describe TLAW::DSL::ApiBuilder do describe '#finalize' do let(:api) { Class.new(TLAW::API) } let(:builder) { described_class.new(api) do base 'http://google.com' namespace :foo do endpoint :bar do end end end } subject { builder.finalize } its(:base_url) { 'http://google.com' } context 'when built for existing class' do before do stub_const('TheAPI', api) end its_block { is_expected.to define_constant('TheAPI::Foo::Bar') } end context 'when built for dynamic class' end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/dsl/endpoint_builder_spec.rb
spec/tlaw/dsl/endpoint_builder_spec.rb
# frozen_string_literal: true require 'tlaw/dsl/endpoint_builder' RSpec.describe TLAW::DSL::EndpointBuilder do describe '#finalize' do let(:builder) { described_class.new(symbol: :foo, path: '/bar/{baz}') do description 'Good description' param :foo, Integer param :quux end } subject { builder.finalize } it { is_expected.to be < TLAW::Endpoint } it { is_expected.to have_attributes( symbol: :foo, path: '/bar/{baz}', description: 'Good description' ) } its(:param_defs) { is_expected.to contain_exactly( have_attributes(name: :baz, keyword?: false), have_attributes(name: :foo, keyword?: true, type: TLAW::Param::ClassType.new(Integer)), have_attributes(name: :quux, type: TLAW::Param::Type.default_type) ) } end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/spec/tlaw/formatting/describe_spec.rb
spec/tlaw/formatting/describe_spec.rb
# frozen_string_literal: true require 'tlaw/formatting/describe' RSpec.describe TLAW::Formatting::Describe do describe '.endpoint_class' do let(:ep) { TLAW::DSL::EndpointBuilder.new(symbol: :foo, path: '/foo') { desc 'The description' docs 'http://example.com' param :a, Integer, keyword: false, required: true, desc: 'It is a param!' param :b, enum: %w[a b], required: true, desc: 'It is another one' }.finalize } subject { described_class.endpoint_class(ep) } it { is_expected.to eq <<~DESC.rstrip foo(a, b:) The description Docs: http://example.com @param a [Integer] It is a param! @param b It is another one Possible values: "a", "b" DESC } end describe '.namespace_class' do let(:ns) { TLAW::DSL::NamespaceBuilder.new(symbol: :foo, path: '/foo') { desc 'The description' param :a, Integer, keyword: false, required: true, desc: 'It is a param!' param :b, enum: %w[a b], required: true, desc: 'It is another one' namespace :nested do desc 'Nested NS' param :c end endpoint :ep do desc 'Nested EP' param :d end }.finalize } subject { described_class.namespace_class(ns) } it { is_expected.to eq <<~DESC.rstrip foo(a, b:) The description @param a [Integer] It is a param! @param b It is another one Possible values: "a", "b" Namespaces: .nested(c: nil) Nested NS Endpoints: .ep(d: nil) Nested EP DESC } end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/open_weather_map.rb
examples/open_weather_map.rb
require 'geo/coord' module TLAW module Examples class OpenWeatherMap < TLAW::API define do desc %Q{ API for [OpenWeatherMap](http://openweathermap.org/). Only parts available for free are implemented (as only them could be tested). } docs 'http://openweathermap.org/api' base 'http://api.openweathermap.org/data/2.5' param :appid, required: true, desc: 'You need to receive it at http://openweathermap.org/appid (free)' param :lang, default: 'en', desc: %Q{Language of API responses (affects weather description only). See http://openweathermap.org/current#multi for list of supported languages.} param :units, enum: %i[standard metric imperial], default: :standard, desc: 'Units for temperature and other values. Standard is Kelvin.' # OpenWeatherMap reports most of logical errors with HTTP code # 200 and responses like {cod: "500", message: "Error message"} post_process { |h| !h.key?('cod') || (200...400).cover?(h['cod'].to_i) or fail "#{h['cod']}: #{h['message']}" } shared_def :lat_lng do param :lat, :to_f, required: true, desc: 'Latitude' param :lng, :to_f, required: true, desc: 'Longitude' end shared_def :cluster do param :cluster, enum: {true => 'yes', false: 'no'}, default: true, desc: 'Use server clustering of points' end WEATHER_POST_PROCESSOR = lambda do |*| # Most of the time there is exactly one weather item... # ...but sometimes there are two. So, flatterning them looks # more reasonable than having DataTable of 1-2 rows. post_process { |h| h['weather2'] = h['weather'].last if h['weather'] && h['weather'].count > 1 } post_process('weather', &:first) post_process('dt', &Time.method(:at)) post_process('dt_txt') { nil } # TODO: we need cleaner way to say "remove this" post_process('sys.sunrise', &Time.method(:at)) post_process('sys.sunset', &Time.method(:at)) # https://github.com/zverok/geo_coord promo here! post_process { |e| e['coord'] = Geo::Coord.new(e['coord.lat'], e['coord.lon']) if e['coord.lat'] && e['coord.lon'] } post_process('coord.lat') { nil } post_process('coord.lon') { nil } # See http://openweathermap.org/weather-conditions#How-to-get-icon-URL post_process('weather.icon', &'http://openweathermap.org/img/w/%s.png'.method(:%)) end # For endpoints returning weather in one place instance_eval(&WEATHER_POST_PROCESSOR) # For endpoints returning list of weathers (forecast or several # cities). post_process_items('list', &WEATHER_POST_PROCESSOR) namespace :current, '/weather' do desc %Q{ Allows to obtain current weather at one place, designated by city, location or zip code. } docs 'http://openweathermap.org/current' endpoint :city, '?q={city}{,country_code}' do desc %Q{ Current weather by city name (with optional country code specification). } docs 'http://openweathermap.org/current#name' param :city, required: true, desc: 'City name' param :country_code, desc: 'ISO 3166 2-letter country code' end endpoint :city_id, '?id={city_id}' do desc %Q{ Current weather by city id. Recommended by OpenWeatherMap docs. List of city ID city.list.json.gz can be downloaded at http://bulk.openweathermap.org/sample/ } docs 'http://openweathermap.org/current#cityid' param :city_id, required: true, desc: 'City ID (as defined by OpenWeatherMap)' end endpoint :location, '?lat={lat}&lon={lng}' do desc %Q{ Current weather by geographic coordinates. } docs 'http://openweathermap.org/current#geo' use_def :lat_lng end endpoint :zip, '?zip={zip}{,country_code}' do desc %Q{ Current weather by ZIP code (with optional country code specification). } docs 'http://openweathermap.org/current#zip' param :zip, required: true, desc: 'ZIP code' param :country_code, desc: 'ISO 3166 2-letter country code' end endpoint :group, '/../group?id={city_ids}' do desc %Q{ Current weather in several cities by their ids. List of city ID city.list.json.gz can be downloaded at http://bulk.openweathermap.org/sample/ } docs 'http://openweathermap.org/current#cities' param :city_ids, :to_a, required: true end end namespace :find do desc %Q{ Allows to find some place (and weather in it) by set of input parameters. } docs 'http://openweathermap.org/current#accuracy' endpoint :by_name, '?q={start_with}{,country_code}' do desc %Q{ Looks for cities by beginning of their names. } docs 'http://openweathermap.org/current#accuracy' param :start_with, required: true, desc: 'Beginning of city name' param :country_code, desc: 'ISO 3166 2-letter country code' param :cnt, :to_i, enum: 1..50, default: 10, desc: 'Max number of results to return' param :accurate, field: :type, enum: {true => 'accurate', false => 'like'}, default: true, desc: %Q{Accuracy level of result. true returns exact match values (accurate). false returns results by searching for that substring (like). } end endpoint :around, '?lat={lat}&lon={lng}' do desc %Q{ Looks for cities around geographical coordinates. } docs 'http://openweathermap.org/current#cycle' use_def :lat_lng param :cnt, :to_i, enum: 1..50, default: 10, desc: 'Max number of results to return' use_def :cluster end # Real path is api/bbox/city - not inside /find, but logically # we want to place it here endpoint :inside, '/../box/city?bbox={lng_left},{lat_bottom},{lng_right},{lat_top},{zoom}' do desc %Q{ Looks for cities inside specified rectangle zone. } docs 'http://openweathermap.org/current#rectangle' param :lat_top, :to_f, required: true, keyword: true param :lat_bottom, :to_f, required: true, keyword: true param :lng_left, :to_f, required: true, keyword: true param :lng_right, :to_f, required: true, keyword: true param :zoom, :to_i, default: 10, keyword: true, desc: 'Map zoom level.' use_def :cluster end end # http://openweathermap.org/forecast5 namespace :forecast do desc %Q{ Allows to obtain weather forecast for 5 days with 3-hour frequency. NB: OpenWeatherMap also implement [16-day forecast](http://openweathermap.org/forecast16), but it have no free option and can not be tested. That's why we don't implement it. } docs 'http://openweathermap.org/forecast5' post_process { |e| e['city.coord'] = Geo::Coord.new(e['city.coord.lat'], e['city.coord.lon']) \ if e['city.coord.lat'] && e['city.coord.lon'] } post_process('city.coord.lat') { nil } post_process('city.coord.lon') { nil } endpoint :city, '?q={city}{,country_code}' do desc %Q{ Weather forecast by city name (with optional country code specification). } docs 'http://openweathermap.org/forecast5#name5' param :city, required: true, desc: 'City name' param :country_code, desc: 'ISO 3166 2-letter country code' end endpoint :city_id, '?id={city_id}' do desc %Q{ Current weather by city id. Recommended by OpenWeatherMap docs. List of city ID city.list.json.gz can be downloaded at http://bulk.openweathermap.org/sample/ } docs 'http://openweathermap.org/forecast5#cityid5' param :city_id, required: true, desc: 'City ID (as defined by OpenWeatherMap)' end endpoint :location, '?lat={lat}&lon={lng}' do desc %Q{ Weather forecast by geographic coordinates. } docs 'http://openweathermap.org/forecast5#geo5' use_def :lat_lng end end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/giphy_demo.rb
examples/giphy_demo.rb
#!/usr/bin/env ruby require_relative 'demo_base' require_relative 'giphy' giphy = TLAW::Examples::Giphy.new(api_key: ENV['GIPHY']) pp giphy.gifs.search('tardis') # => {"data"=> # #<TLAW::DataTable[type, id, slug, url, bitly_gif_url, bitly_url, embed_url, username, source, rating, content_url, source_tld, source_post_url, is_indexable, import_datetime, trending_datetime, images.fixed_height_still.url, images.fixed_height_still.width, images.fixed_height_still.height, images.original_still.url, images.original_still.width, images.original_still.height, images.fixed_width.url, images.fixed_width.width, images.fixed_width.height, images.fixed_width.size, images.fixed_width.mp4, images.fixed_width.mp4_size, images.fixed_width.webp, images.fixed_width.webp_size, images.fixed_height_small_still.url, images.fixed_height_small_still.width, images.fixed_height_small_still.height, images.fixed_height_downsampled.url, images.fixed_height_downsampled.width, images.fixed_height_downsampled.height, images.fixed_height_downsampled.size, images.fixed_height_downsampled.webp, images.fixed_height_downsampled.webp_size, images.preview.width, images.preview.height, images.preview.mp4, images.preview.mp4_size, images.fixed_height_small.url, images.fixed_height_small.width, images.fixed_height_small.height, images.fixed_height_small.size, images.fixed_height_small.mp4, images.fixed_height_small.mp4_size, images.fixed_height_small.webp, images.fixed_height_small.webp_size, images.downsized_still.url, images.downsized_still.width, images.downsized_still.height, images.downsized_still.size, images.downsized.url, images.downsized.width, images.downsized.height, images.downsized.size, images.downsized_large.url, images.downsized_large.width, images.downsized_large.height, images.downsized_large.size, images.fixed_width_small_still.url, images.fixed_width_small_still.width, images.fixed_width_small_still.height, images.preview_webp.url, images.preview_webp.width, images.preview_webp.height, images.preview_webp.size, images.fixed_width_still.url, images.fixed_width_still.width, images.fixed_width_still.height, images.fixed_width_small.url, images.fixed_width_small.width, images.fixed_width_small.height, images.fixed_width_small.size, images.fixed_width_small.mp4, images.fixed_width_small.mp4_size, images.fixed_width_small.webp, images.fixed_width_small.webp_size, images.downsized_small.width, images.downsized_small.height, images.downsized_small.mp4, images.downsized_small.mp4_size, images.fixed_width_downsampled.url, images.fixed_width_downsampled.width, images.fixed_width_downsampled.height, images.fixed_width_downsampled.size, images.fixed_width_downsampled.webp, images.fixed_width_downsampled.webp_size, images.downsized_medium.url, images.downsized_medium.width, images.downsized_medium.height, images.downsized_medium.size, images.original.url, images.original.width, images.original.height, images.original.size, images.original.frames, images.original.mp4, images.original.mp4_size, images.original.webp, images.original.webp_size, images.fixed_height.url, images.fixed_height.width, images.fixed_height.height, images.fixed_height.size, images.fixed_height.mp4, images.fixed_height.mp4_size, images.fixed_height.webp, images.fixed_height.webp_size, images.looping.mp4, images.looping.mp4_size, images.original_mp4.width, images.original_mp4.height, images.original_mp4.mp4, images.original_mp4.mp4_size, images.preview_gif.url, images.preview_gif.width, images.preview_gif.height, images.preview_gif.size, user.avatar_url, user.banner_url, user.profile_url, user.username, user.display_name, user.twitter, images.fixed_height_still.size, images.original_still.size, images.fixed_height_small_still.size, images.fixed_width_small_still.size, images.fixed_width_still.size, images.original.hash, images.hd.width, images.hd.height, images.hd.mp4, images.hd.mp4_size, images.480w_still.url, images.480w_still.width, images.480w_still.height, images.480w_still.size] x 25>, # "pagination.total_count"=>1559, # "pagination.count"=>25, # "pagination.offset"=>0, # "meta.status"=>200, # "meta.msg"=>"OK", # "meta.response_id"=>"597d9b7b6b56594f3259f254"} # pp giphy.gifs.search('tardis')['data'].first # => # {"type"=>"gif", # "id"=>"yp2qzMjcEQVB6", # "slug"=>"tardis-doctor-who-deer-yp2qzMjcEQVB6", # "url"=>"https://giphy.com/gifs/tardis-doctor-who-deer-yp2qzMjcEQVB6", # "bitly_gif_url"=>"http://gph.is/XN3l6K", # "bitly_url"=>"http://gph.is/XN3l6K", # "embed_url"=>"https://giphy.com/embed/yp2qzMjcEQVB6", # "username"=>"", # "source"=>"http://doctorwhogifs.tumblr.com/post/38804044036", # "rating"=>"y", # "content_url"=>"", # "source_tld"=>"doctorwhogifs.tumblr.com", # "source_post_url"=>"http://doctorwhogifs.tumblr.com/post/38804044036", # "is_indexable"=>0, # "import_datetime"=>"2013-03-21 05:57:22", # "trending_datetime"=>"1970-01-01 00:00:00", # "images.fixed_height_still.url"=> # "https://media0.giphy.com/media/yp2qzMjcEQVB6/200_s.gif", # "images.fixed_height_still.width"=>346, # "images.fixed_height_still.height"=>200, # "images.original_still.url"=> # "https://media2.giphy.com/media/yp2qzMjcEQVB6/giphy_s.gif", # "images.original_still.width"=>360, # "images.original_still.height"=>208, # "images.fixed_width.url"=> # "https://media1.giphy.com/media/yp2qzMjcEQVB6/200w.gif", # "images.fixed_width.width"=>200, # "images.fixed_width.height"=>116, # "images.fixed_width.size"=>37396, # "images.fixed_width.mp4"=> # "https://media2.giphy.com/media/yp2qzMjcEQVB6/200w.mp4", # "images.fixed_width.mp4_size"=>13349, # "images.fixed_width.webp"=> # "https://media2.giphy.com/media/yp2qzMjcEQVB6/200w.webp", # "images.fixed_width.webp_size"=>61238, # ...and so on, there are several types of images # Inspectability: TLAW::Examples::Giphy # => #<TLAW::Examples::Giphy: call-sequence: TLAW::Examples::Giphy.new(api_key:, lang: nil); namespaces: gifs, stickers; docs: .describe> giphy # => #<TLAW::Examples::Giphy.new(api_key: nil, lang: nil) namespaces: gifs, stickers; docs: .describe> giphy.describe # => TLAW::Examples::Giphy.new(api_key: nil, lang: nil) # Wrapper for [Giphy](https://giphy.com/) GIF hosting service API. # # Docs: https://developers.giphy.com/docs/ # # @param api_key For development, create it at your [dashboard](https://developers.giphy.com/dashboard/?create=true). # Note that you'll need to request different key for production use. # @param lang 2-letter ISO 639-1 language code. # [Full list of supported languages](https://developers.giphy.com/docs/) # # Namespaces: # # .gifs() # Fetch GIPHY GIFs. # # .stickers() # Fetch GIPHY stickers (GIFs with transparent background). giphy.namespace(:gifs).describe # => .gifs() # Fetch GIPHY GIFs. # # Endpoints: # # .search(query, limit: nil, offset: nil, rating: nil) # Search all GIFs by word or phrase. # # .trending(limit: nil, rating: nil) # Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team. # # .translate(phrase) # Translates phrase to GIFs "vocabulary". # # .random(tag: nil, rating: nil) # Returns a random GIF, optionally limited by tag. # # .[](id) # One GIF by unique id. # # .multiple(ids) # Sevaral GIFs by unique ids.
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/giphy.rb
examples/giphy.rb
require 'pp' $:.unshift 'lib' require 'tlaw' module TLAW module Examples class Giphy < TLAW::API define do desc %Q{ Wrapper for [Giphy](https://giphy.com/) GIF hosting service API. } docs 'https://developers.giphy.com/docs/' base 'http://api.giphy.com/v1' param :api_key, required: true, desc: %Q{For development, create it at your [dashboard](https://developers.giphy.com/dashboard/?create=true). Note that you'll need to request different key for production use.} param :lang, desc: %Q{2-letter ISO 639-1 language code. [Full list of supported languages](https://developers.giphy.com/docs/)} %i[gifs stickers].each do |ns| namespace ns do if ns == :gifs desc 'Fetch GIPHY GIFs.' else desc 'Fetch GIPHY stickers (GIFs with transparent background).' end post_process_items('data') do post_process(/\.(size|mp4_size|webp_size|width|height|frames)/, &:to_i) end endpoint :search do desc 'Search all GIFs by word or phrase.' param :query, field: :q, keyword: false, required: true, desc: 'Search string' param :limit, :to_i, desc: 'Max number of results to return' param :offset, :to_i, desc: 'Results offset' param :rating, enum: %w[y g pg pg-13 r unrated nsfw], desc: 'Parental advisory rating' end endpoint :trending do desc 'Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team.' param :limit, :to_i, desc: 'Max number of results to return' param :rating, enum: %w[y g pg pg-13 r unrated nsfw], desc: 'Parental advisory rating' end endpoint :translate do desc 'Translates phrase to GIFs "vocabulary".' param :phrase, field: :s, keyword: false, required: true, desc: 'Phrase to translate' post_process(/\.(size|mp4_size|webp_size|width|height|frames)/, &:to_i) end endpoint :random do desc 'Returns a random GIF, optionally limited by tag.' param :tag param :rating, desc: 'Parental advisory rating' end end end namespace :gifs do endpoint :[], '/{id}' do desc 'One GIF by unique id.' param :id, required: true end endpoint :multiple, '/?ids={ids}' do desc 'Sevaral GIFs by unique ids.' param :ids, :to_a, required: true end end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/open_weather_map_demo.rb
examples/open_weather_map_demo.rb
#!/usr/bin/env ruby require_relative 'demo_base' require_relative 'open_weather_map' # This is demonstration of TLAW (The Last API Wrapper) library's behavior # and opinions. # # All of below functionality is created by this API wrapper definition: # TODO URL # OK, first thing is: all API wrappers created with TLAW, are # _discoverable_ by design. In fact, you can understand all you need to # use the API just from IRB, no need to go to rdoc.info, dig in code, # or, my favourite thing, "see arguments explanation at original API # site". # Let's see: p TLAW::Examples::OpenWeatherMap # => #<TLAW::Examples::OpenWeatherMap: call-sequence: TLAW::Examples::OpenWeatherMap.new(appid:, lang: "en", units: :standard); namespaces: current, find, forecast; docs: .describe> # Let's try this .describe thing which inspect recommends: p TLAW::Examples::OpenWeatherMap.describe # TLAW::Examples::OpenWeatherMap.new(appid:, lang: "en", units: :standard) # API for [OpenWeatherMap](http://openweathermap.org/). Only parts # available for free are implemented (as only them could be tested). # # See full docs at http://openweathermap.org/api # # @param appid You need to receive it at http://openweathermap.org/appid (free) # @param lang Language of API responses (affects weather description only). # See http://openweathermap.org/current#multi for list of supported languages. (default = "en") # @param units Units for temperature and other values. Standard is Kelvin. # Possible values: :standard, :metric, :imperial (default = :standard) # # Namespaces: # # .current() # Allows to obtain current weather at one place, designated # by city, location or zip code. # # .find() # Allows to find some place (and weather in it) by set of input # parameters. # # .forecast() # Allows to obtain weather forecast for 5 days with 3-hour # frequency. # Note that this multiline output is produced by `p`! So, in IRB/pry # session it would be exactly the same: you just say "something.describe", # and it is just printed the most convenient way. # Let's look closer to some of those namespaces: p TLAW::Examples::OpenWeatherMap.namespace(:current) # => #<TLAW::Examples::OpenWeatherMap::Current: call-sequence: current(); endpoints: city, city_id, location, zip, group; docs: .describe> # .describe, anyone? p TLAW::Examples::OpenWeatherMap.namespace(:current).describe # .current() # Allows to obtain current weather at one place, designated # by city, location or zip code. # # Docs: http://openweathermap.org/current # # # Endpoints: # # .city(city, country_code=nil) # Current weather by city name (with optional country code # specification). # # .city_id(city_id) # Current weather by city id. Recommended by OpenWeatherMap # docs. # # .location(lat, lng) # Current weather by geographic coordinates. # # .zip(zip, country_code=nil) # Current weather by ZIP code (with optional country code # specification). # # .group(city_ids) # Current weather in several cities by their ids. # And further: p TLAW::Examples::OpenWeatherMap .namespace(:current).endpoint(:city) # => #<TLAW::Examples::OpenWeatherMap::Current::City: call-sequence: city(city, country_code=nil); docs: .describe> p TLAW::Examples::OpenWeatherMap .namespace(:current).endpoint(:city).describe # .city(city, country_code=nil) # Current weather by city name (with optional country code # specification). # # Docs: http://openweathermap.org/current#name # # @param city City name # @param country_code ISO 3166 2-letter country code # Note, that all above classes and methods are generated at moment of # API definition, so there is no cumbersome dispatching at runtime: p TLAW::Examples::OpenWeatherMap.instance_methods(false) # => [:current, :find, :forecast] p TLAW::Examples::OpenWeatherMap::Current.instance_methods(false) # => [:city, :city_id, :location, :zip, :group] p TLAW::Examples::OpenWeatherMap::Current.instance_method(:city).parameters # => [[:req, :city], [:opt, :country_code]] # E.g. namespace is a class, providing methods for all the child # namespaces and endpoints! And all params are just method params. # OK, let's go for some real things, not just documentation reading. # You need to create key here: http://openweathermap.org/appid # And run the script this way: # # OPEN_WEATHER_MAP={your_id} examples/open_weather_map_demo.rb # weather = TLAW::Examples::OpenWeatherMap .new(appid: ENV['OPEN_WEATHER_MAP'], units: :metric) p weather # => #<TLAW::Examples::OpenWeatherMap.new(appid: {your id}, lang: nil, units: :metric) namespaces: current, find, forecast; docs: .describe> # Looks familiar and nothing new. p weather.current # => #<current() endpoints: city, city_id, location, zip, group; docs: .describe> # Saem. pp weather.current.city('Kharkiv') # {"weather.id"=>800, # "weather.main"=>"Clear", # "weather.description"=>"clear sky", # "weather.icon"=>"http://openweathermap.org/img/w/01n.png", # "base"=>"cmc stations", # "main.temp"=>23, # "main.pressure"=>1013, # "main.humidity"=>40, # "main.temp_min"=>23, # "main.temp_max"=>23, # "wind.speed"=>2, # "wind.deg"=>190, # "clouds.all"=>0, # "dt"=>2016-09-05 20:30:00 +0300, # "sys.type"=>1, # "sys.id"=>7355, # "sys.message"=>0.0115, # "sys.country"=>"UA", # "sys.sunrise"=>2016-09-05 05:57:26 +0300, # "sys.sunset"=>2016-09-05 19:08:13 +0300, # "id"=>706483, # "name"=>"Kharkiv", # "cod"=>200, # "coord"=>#<Geo::Coord 50.000000,36.250000>} # Whoa! # # What we see here (except for "OK, it works")? # # Several pretty improtant things: # # * TLAW response processing is _highly opinionated_. It tends do flatten # all the hashes: original has something like # {weather: {...}, main: {...}, sys: {...} # * It is done, again, for the sake of _discoverability_. You, like, see # at once all things API response proposes; you can do `response.keys` # to understand what you got instead of `response.keys`, hm, # `response['weather'].class`, ah, ok, `response['weather'].keys` and # so on; # * TLAW allows easy postprocessing of response: our example API parses # timestamps into proper ruby times, and (just to promote related gem), # converts "coord.lat" and "coord.lng" to one instance of a Geo::Coord, # from https://github.com/zverok/geo_coord # # Finally, one HUGE design decision related to "opinionated response # processing": pp weather.forecast.city('Kharkiv') # {"city.id"=>706483, # "city.name"=>"Kharkiv", # "city.country"=>"UA", # "city.population"=>0, # "city.sys.population"=>0, # "cod"=>"200", # "message"=>0.0276, # "cnt"=>40, # "list"=> # #<TLAW::DataTable[dt, main.temp, main.temp_min, main.temp_max, main.pressure, main.sea_level, main.grnd_level, main.humidity, main.temp_kf, weather.id, weather.main, weather.description, weather.icon, clouds.all, wind.speed, wind.deg, sys.pod] x 40>, # "city.coord"=>#<Geo::Coord 50.000000,36.250000>} # Hmm? What is this DataTable thingy? It is (loosy) implementation of # DataFrame data type. You can think of it as an array of homogenous # hashes -- which could be considered the main type of useful JSON API # data. forecasts = weather.forecast.city('Kharkiv')['list'] p forecasts.count # => 40 p forecasts.keys # => ["dt", "main.temp", "main.temp_min", "main.temp_max", "main.pressure", "main.sea_level", "main.grnd_level", "main.humidity", "main.temp_kf", "weather.id", "weather.main", "weather.description", "weather.icon", "clouds.all", "wind.speed", "wind.deg", "sys.pod"] p forecasts.first # => {"dt"=>2016-09-06 00:00:00 +0300, "main.temp"=>12.67, "main.temp_min"=>12.67, "main.temp_max"=>15.84, "main.pressure"=>1006.67, "main.sea_level"=>1026.62, "main.grnd_level"=>1006.67, "main.humidity"=>74, "main.temp_kf"=>-3.17, "weather.id"=>800, "weather.main"=>"Clear", "weather.description"=>"clear sky", "weather.icon"=>"http://openweathermap.org/img/w/01n.png", "clouds.all"=>0, "wind.speed"=>1.26, "wind.deg"=>218.509, "sys.pod"=>"n"} p forecasts['dt'].first(3) # => [2016-09-06 00:00:00 +0300, 2016-09-06 03:00:00 +0300, 2016-09-06 06:00:00 +0300] p forecasts.columns('dt', 'main.temp').to_a.first(3) # => [{"dt"=>2016-09-06 00:00:00 +0300, "main.temp"=>12.67}, {"dt"=>2016-09-06 03:00:00 +0300, "main.temp"=>11.65}, {"dt"=>2016-09-06 06:00:00 +0300, "main.temp"=>12.41}] # All of it works and you can check it by yourself. # # Again, EVERYTHING you can see in this example is created by short and # focused API definition: TODO URL
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/forecast_io_demo.rb
examples/forecast_io_demo.rb
#!/usr/bin/env ruby require_relative 'demo_base' require_relative 'forecast_io' # This wrapper demo demonstrates that even a simple (one call, several # params) API could benefit from TLAW by param types checking & # sky-level discoverability. p TLAW::Examples::ForecastIO # #<TLAW::Examples::ForecastIO: call-sequence: TLAW::Examples::ForecastIO.new(api_key:, units: :us, lang: :en); endpoints: forecast, time_machine; docs: .describe> p TLAW::Examples::ForecastIO.describe # TLAW::Examples::ForecastIO.new(api_key:, units: :us, lang: :en) # The Forecast API allows you to look up the weather anywhere on # the globe, returning (where available): # # * Current conditions # * Minute-by-minute forecasts out to 1 hour # * Hour-by-hour forecasts out to 48 hours # * Day-by-day forecasts out to 7 days # # Docs: https://developer.forecast.io/docs/v2 # # @param api_key Register at https://developer.forecast.io/register to obtain it # @param units # Response units. Values: # * `:us` is default; # * `:si` is meters/celsius/hectopascals; # * `:ca` is identical to si, except that `windSpeed` is in # kilometers per hour. # * `:uk2` is identical to si, except that `windSpeed` is in # miles per hour, and `nearestStormDistance` and `visibility` # are in miles, as in the US. # * `auto` selects the relevant units automatically, based # on geographic location. # # Possible values: :us, :si, :ca, :uk2, :auto (default = :us) # @param lang # Return summary properties in the desired language. (2-letters code) # (default = :en) # # Endpoints: # # .forecast(lat, lng, exclude: nil, extended_hourly: nil) # Forecast for the next week. # # .time_machine(lat, lng, at, exclude: nil) # Observed weather at a given time (for many places, up to 60 # years in the past). # You need to create key here: https://developer.forecast.io/register # And run the script this way: # # FORECAST_IO={your_id} examples/forecast_io_demo.rb # weather = TLAW::Examples::ForecastIO .new(api_key: ENV['FORECAST_IO'], units: :si) res = weather.forecast(40.7127, -74.0059, extended_hourly: true) pp res # {"latitude"=>40.7127, # "longitude"=>-74.0059, # "timezone"=>"America/New_York", # "offset"=>-5, # "currently.time"=>2017-02-23 19:06:50 +0200, # "currently.summary"=>"Overcast", # "currently.icon"=>"cloudy", # "currently.nearestStormDistance"=>362, # "currently.nearestStormBearing"=>179, # "currently.precipIntensity"=>0, # "currently.precipProbability"=>0, # "currently.temperature"=>12.57, # "currently.apparentTemperature"=>12.57, # "currently.dewPoint"=>10.42, # "currently.humidity"=>0.87, # "currently.windSpeed"=>2.03, # "currently.windBearing"=>188, # "currently.visibility"=>9.69, # "currently.cloudCover"=>0.95, # "currently.pressure"=>1012.11, # "currently.ozone"=>330.56, # "minutely.summary"=>"Overcast for the hour.", # "minutely.icon"=>"cloudy", # "minutely.data"=> # #<TLAW::DataTable[time, precipIntensity, precipProbability] x 61>, # "hourly.summary"=>"Light rain starting this evening.", # "hourly.icon"=>"rain", # "hourly.data"=> # #<TLAW::DataTable[time, summary, icon, precipIntensity, precipProbability, temperature, apparentTemperature, dewPoint, humidity, windSpeed, windBearing, visibility, cloudCover, pressure, ozone, precipType] x 169>, # "daily.summary"=> # "Light rain throughout the week, with temperatures falling to 12°C on Thursday.", # "daily.icon"=>"rain", # "daily.data"=> # #<TLAW::DataTable[time, summary, icon, sunriseTime, sunsetTime, moonPhase, precipIntensity, precipIntensityMax, precipIntensityMaxTime, precipProbability, precipType, temperatureMin, temperatureMinTime, temperatureMax, temperatureMaxTime, apparentTemperatureMin, apparentTemperatureMinTime, apparentTemperatureMax, apparentTemperatureMaxTime, dewPoint, humidity, windSpeed, windBearing, visibility, cloudCover, pressure, ozone] x 8>, # "flags.sources"=> ["darksky", "lamp", "gfs", "cmc", "nam", "rap", "rtma", "sref", "fnmoc", "isd", "madis", "nearest-precip", "nwspa"], # "flags.darksky-stations"=>["KDIX", "KOKX"], # "flags.lamp-stations"=> ["KBLM", "KCDW", "KEWR", "KFRG", "KHPN", "KJFK", "KLGA", "KMMU", "KNYC", "KSMQ", "KTEB"], # "flags.isd-stations"=> ["725020-14734", "725025-94741", "725030-14732", "725033-94728", "725060-99999", "744860-94789", "744976-99999", "997271-99999", "997272-99999", "997743-99999", "999999-14732", "999999-14734", "999999-14786", "999999-94706", "999999-94728", "999999-94741"], # "flags.madis-stations"=> ["AU015", "BATN6", "C1099", "C9714", "D0486", "D3216", "D5729", "D9152", "E0405", "E1296", "E2876", "KLGA", "KNYC", "KTEB", "NJ12", "ROBN4"], # "flags.units"=>"si"} pp res['minutely.data'].first # {"time"=>2016-09-12 21:20:00 +0300, # "precipIntensity"=>0, # "precipProbability"=>0} res = weather.time_machine(49.999892, 36.242392, Date.parse('2020-02-01')) pp res['daily.data'].columns('time', 'temperatureMin', 'temperatureMax', 'dewPoint', 'moonPhase').first # {"time"=>2020-02-01 00:00:00 +0200, # "temperatureMin"=>-6.61, # "temperatureMax"=>-4.37, # "dewPoint"=>-7.7, # "moonPhase"=>0.23}
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/tmdb_demo.rb
examples/tmdb_demo.rb
#!/usr/bin/env ruby require_relative 'demo_base' # This example demonstrates how TLAW allows you to define and redefine # API wrappers on the fly—to the extent you need and without much # bothering—and still have all the goodies. # For example, you have pretty large and complicated TheMoviesDatabase API: # http://docs.themoviedb.apiary.io/ # ...and all you want is just to search for movies and get their posters. # All existing TMDB Ruby wrappers (I know at least three) are strange. # # What you'll do? # # That's what: class TMDB < TLAW::API define do base 'http://api.themoviedb.org/3' param :api_key, required: true param :language, default: 'en' namespace :movies, '/movie' do namespace :[], '/{id}' do param :id, required: true endpoint :images end end namespace :search do endpoint :movie do param :query, required: true, keyword: false post_process_items('results') { post_process 'release_date', &Date.method(:parse) } end end end end # You need to run it like TMDB={your_key} ./examples/tmdb_demo.rb tmdb = TMDB.new(api_key: ENV['TMDB']) pp tmdb.search.movie('guardians of the galaxy') # {"page"=>1, # "results"=> # #<TLAW::DataTable[poster_path, adult, overview, release_date, genre_ids, id, original_title, original_language, title, backdrop_path, popularity, vote_count, video, vote_average] x 2>, # "total_results"=>2, # "total_pages"=>1} pp tmdb.search.movie('guardians of the galaxy')['results'].first # {"poster_path"=>"/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg", # "adult"=>false, # "overview"=> # "Light years from Earth, 26 years after being abducted, Peter Quill finds himself the prime target of a manhunt after discovering an orb wanted by Ronan the Accuser.", # "release_date"=>#<Date: 2014-07-30 ((2456869j,0s,0n),+0s,2299161j)>, # "genre_ids"=>[28, 878, 12], # "id"=>118340, # "original_title"=>"Guardians of the Galaxy", # "original_language"=>"en", # "title"=>"Guardians of the Galaxy", # "backdrop_path"=>"/bHarw8xrmQeqf3t8HpuMY7zoK4x.jpg", # "popularity"=>12.287455, # "vote_count"=>5067, # "video"=>false, # "vote_average"=>7.96} # OK, now we have an id pp tmdb.movies[118340].images # Note, that [] is also namespace accessor here :) With param. See API # description above. pp tmdb.movies[118340].images['posters'].last # {"aspect_ratio"=>0.666666666666667, # "file_path"=>"/6YUodKKkqIIDx6Hk7ZkaVOxnWND.jpg", # "height"=>1500, # "iso_639_1"=>"ru", # "vote_average"=>0.0, # "vote_count"=>0, # "width"=>1000} # Hmm, maybe we need some path post-processing?.. How about adding it # right now? Assuming our API is already described by someone else... tmdb.class.define do namespace :movies do namespace :[] do endpoint :images do post_process_items 'posters' do post_process('file_path') { |p| 'https://image.tmdb.org/t/p/original' + p } end end end end end pp tmdb.movies[118340].images['posters'].last # Ah, much better! # # {"aspect_ratio"=>0.666666666666667, # "file_path"=> # "https://image.tmdb.org/t/p/original/6YUodKKkqIIDx6Hk7ZkaVOxnWND.jpg", # "height"=>1500, # "iso_639_1"=>"ru", # "vote_average"=>0.0, # "vote_count"=>0, # "width"=>1000} # Note, that despite not adding a bit of documentation, you still have # your API wrapper discoverable: p TMDB # #<TMDB: call-sequence: TMDB.new(api_key:, language: "en"); namespaces: movies, search; docs: .describe> p tmdb.movies.describe # .movies() # # # Namespaces: # # .[](id) p tmdb.movies.namespace(:[]).describe # .[](id) # @param id # # Endpoints: # # .images() # So, you can still investigate, navigate and get meaningful API errors # with backtraces... While you spent only like 15 lines on API description.
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/forecast_io.rb
examples/forecast_io.rb
module TLAW module Examples class ForecastIO < TLAW::API define do base 'https://api.forecast.io/forecast/{api_key}' desc %Q{ The Forecast API allows you to look up the weather anywhere on the globe, returning (where available): * Current conditions * Minute-by-minute forecasts out to 1 hour * Hour-by-hour forecasts out to 48 hours * Day-by-day forecasts out to 7 days } docs 'https://developer.forecast.io/docs/v2' param :api_key, required: true, desc: 'Register at https://developer.forecast.io/register to obtain it' param :units, enum: %i[us si ca uk2 auto], default: :us, desc: %Q{ Response units. Values: * `:us` is default; * `:si` is meters/celsius/hectopascals; * `:ca` is identical to si, except that `windSpeed` is in kilometers per hour. * `:uk2` is identical to si, except that `windSpeed` is in miles per hour, and `nearestStormDistance` and `visibility` are in miles, as in the US. * `auto` selects the relevant units automatically, based on geographic location. } param :lang, default: :en, desc: %Q{ Return summary properties in the desired language. (2-letters code) } post_process 'currently.time', &Time.method(:at) post_process_items('minutely.data') { post_process 'time', &Time.method(:at) } post_process_items('hourly.data') { post_process 'time', &Time.method(:at) } post_process_items('daily.data') { post_process 'time', &Time.method(:at) post_process 'sunriseTime', &Time.method(:at) post_process 'sunsetTime', &Time.method(:at) } endpoint :forecast, '/{lat},{lng}' do desc %Q{Forecast for the next week.} docs 'https://developer.forecast.io/docs/v2#forecast_call' param :lat, :to_f, required: true, desc: 'Latitude' param :lng, :to_f, required: true, desc: 'Longitude' param :exclude, Array, desc: %Q{ Exclude some number of data blocks from the API response. This is useful for reducing latency and saving cache space. Should be a list (without spaces) of any of the following: currently, minutely, hourly, daily, alerts, flags. } param :extended_hourly, field: :extend, enum: {false => nil, true => 'hourly'}, desc: %Q{ When present, return hourly data for the next seven days, rather than the next two. } end endpoint :time_machine, '/{lat},{lng},{at}' do desc %Q{ Observed weather at a given time (for many places, up to 60 years in the past). For future dates, returns numerical forecast for the next week and seasonal averages beyond that. } docs 'https://developer.forecast.io/docs/v2#time_call' param :lat, :to_f, required: true, desc: 'Latitude' param :lng, :to_f, required: true, desc: 'Longitude' param :at, :to_time, format: :to_i, required: true, desc: 'Date in past or future.' param :exclude, Array, desc: %Q{ Exclude some number of data blocks from the API response. This is useful for reducing latency and saving cache space. Should be a list (without spaces) of any of the following: currently, minutely, hourly, daily, alerts, flags. } end end end # TODO: X-Forecast-API-Calls header is useful! # TODO: The Forecast Data API supports HTTP compression. # We heartily recommend using it, as it will make responses much # smaller over the wire. To enable it, simply add an # Accept-Encoding: gzip header to your request. end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/demo_base.rb
examples/demo_base.rb
$:.unshift File.expand_path('../../lib', __FILE__) require 'tlaw' require 'pp' begin require 'dotenv' Dotenv.load rescue LoadError end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/urbandictionary_demo.rb
examples/urbandictionary_demo.rb
#!/usr/bin/env ruby require_relative 'demo_base' # That's an example of TLAW's strength. # # Urbandictionary API is really small (just two endpoints, only one of # which is actually useful, because /random is more like a joke). # # But you still need to remember the protocol, parse the answer and so # on. # # There is even separate gem: https://github.com/ryangreenberg/urban_dictionary # Its `lib` folder contains 7 files, 9 classes/modules and 300 lines of # code, I kid you not. # # I have no intention to offend that gem's author! I just saying that's # what you get when you need to design everything from scratch, like HTTP # client and params processing and response parsing and whatnot. # # Oh, and there is another one: https://github.com/tmiller/urban # # But when somebody really need them (for chatbots), they use neither, # just redefine everything from scratch with rough net connection and # response parsing (because both of aforementioned gems are too thick # wrappers to rely on them): # * https://github.com/jimmycuadra/lita-urban-dictionary # * https://github.com/cinchrb/cinch-urbandictionary # # Here is our version (17 codelines, including namespacing and bit of # docs, API definition itself takes like 7 lines only): # module TLAW module Examples class UrbanDictionary < TLAW::API define do desc <<~D Really small API. Described as "official but undocumented" by some. D base 'http://api.urbandictionary.com/v0' endpoint :define, '/define?term={term}' do param :term, required: true end endpoint :random, '/random' end end end end # Usage (response is clear as tears, could be integrated anywhere): d = TLAW::Examples::UrbanDictionary.new p d.describe # TLAW::Examples::UrbanDictionary.new() # Really small API. Described as "official but undocumented" # by some. # # Endpoints: # # .define(term) # # .random() res = d.define('trollface') pp res # {"tags"=> # ["troll", # "trolling", # "meme", # "4chan", # "troll face", # "coolface", # "trollfacing", # "trolls", # "backpfeifengesicht", # "derp"], # "result_type"=>"exact", # "list"=> # #<TLAW::DataTable[definition, permalink, thumbs_up, author, word, defid, current_vote, example, thumbs_down] x 7>, # "sounds"=>[]} pp res['list'].columns('word', 'thumbs_up', 'thumbs_down').to_a # [{"word"=>"Trollface", "thumbs_up"=>418, "thumbs_down"=>99}, # {"word"=>"Troll Face", "thumbs_up"=>481, "thumbs_down"=>318}, # {"word"=>"Troll Face", "thumbs_up"=>340, "thumbs_down"=>184}, # {"word"=>"trollface", "thumbs_up"=>115, "thumbs_down"=>35}, # {"word"=>"trollface", "thumbs_up"=>94, "thumbs_down"=>30}, # {"word"=>"trollface", "thumbs_up"=>61, "thumbs_down"=>54}, # {"word"=>"Troll Face", "thumbs_up"=>81, "thumbs_down"=>181}] pp d.random['list'].columns('word', 'example').first(3).to_a # [{"word"=>"pH", "example"=>"Get that ph out of the shower.\r\n\r\n "}, # {"word"=>"spocking", # "example"=> # "The dirty bitch couldn’t get enough so I gave her a damn good spocking"}, # {"word"=>"mormon", # "example"=> # "Oh my gosh are the Smiths mormons?! We better have a party so they can bring some frickin' sweet green jello!..."}] # That's it ¯\_(ツ)_/¯
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/open_route.rb
examples/experimental/open_route.rb
require_relative '../demo_base' require 'geo/coord' class OpenRouteService < TLAW::API define do base 'https://api.openrouteservice.org' param :api_key endpoint :directions do post_process { |res| res['route'] = res['routes'].first } param :coordinates, :to_a, keyword: false, format: ->(coords) { coords.map { |c| c.latlng.join(',') }.join('|') } param :profile param :geometry param :geometry_format end end end osm = OpenRouteService.new(api_key: ENV['OPEN_ROUTE_SERVICE']) kharkiv = Geo::Coord.new(50.004444,36.231389) kyiv = Geo::Coord.new(50.450000,30.523333) pp osm.directions([kharkiv, kyiv], profile: 'driving-car', geometry_format: 'geojson')['route.segments'].first['steps']
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/bing_maps.rb
examples/experimental/bing_maps.rb
require_relative '../demo_base' #http://docs.themoviedb.apiary.io/#reference/movies/movielatest class BingMaps < TLAW::API define do base 'http://dev.virtualearth.net/REST/v1' param :key, required: true namespace :locations, '/Locations' do endpoint :query, '?q={q}' end end end maps = BingMaps.new(key: ENV['BING_MAPS']) pp maps.locations.query('Харків, Олексіівська 33а')['resourceSets'].first
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/quandl.rb
examples/experimental/quandl.rb
require 'pp' $:.unshift 'lib' require 'tlaw' # https://www.quandl.com/docs/api?json#get-data class Quandl < TLAW::API define do base 'https://www.quandl.com/api/v3' param :api_key, required: true namespace :databases do endpoint :list, path: '.json' do param :per_page, :to_i end endpoint :search, '.json?query={query}' do param :query, required: true end namespace :[], '/{code}' do endpoint :meta, '.json' endpoint :codes, '/codes.csv' namespace :datasets, '/../../datasets/{code}' do endpoint :[], '/{dataset_code}.json' do param :code post_process { |h| columns = h['dataset.column_names'] h['dataset.data'] = h['dataset.data'] .map { |r| columns.zip(r).to_h } } post_process_items 'dataset.data' do post_process 'Date', &Date.method(:parse) end end end end end end end q = Quandl.new(api_key: ENV['QUANDL']) #pp q.databases.search('ukraine')['databases'].first pp q.databases['WIKI'].datasets['AAPL', code: 'WIKI']['dataset.data']['Date'].min #pp q.databases['WIKI'].datasets.endpoint(:[]).construct_template
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/airvisual.rb
examples/experimental/airvisual.rb
require_relative '../demo_base' class AirVisual < TLAW::API define do base 'http://api.airvisual.com/v1' param :key, required: true endpoint :nearest, '/nearest?lat={latitude}&lon={longitude}' do end end end av = AirVisual.new(key: ENV['AIRVISUAL']) pp av.nearest(50.004444, 36.231389)
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/tmdb.rb
examples/experimental/tmdb.rb
require 'pp' $:.unshift 'lib' require 'tlaw' #http://docs.themoviedb.apiary.io/#reference/movies/movielatest class TMDB < TLAW::API define do base 'http://api.themoviedb.org/3' param :api_key, required: true param :language, default: 'en' namespace :movies, '/movie' do namespace :[], '/{id}' do param :id, required: true endpoint :get, '' endpoint :alt_titles endpoint :images end endpoint :latest endpoint :now_playing do param :page, :to_i, default: 1 # TODO: validate: 1..1000 end endpoint :upcoming end namespace :search do endpoint :movie do param :query, required: true, keyword: false #post_process_items 'results', 'release_date', &Date.method(:parse) # TODO: post-process image pathes! end end # TODO: should work! #post_process_items 'results', 'release_date', &Date.method(:parse) end end tmdb = TMDB.new(api_key: ENV['TMDB'], language: 'uk') #pp tmdb.movies.upcoming['results'].columns(:release_date, :title).to_a #pp tmdb.movies[413898].images #p tmdb.describe #pp tmdb.search.movie('Terminator')['results'].first p tmdb.movies[1187043].get
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/apixu.rb
examples/experimental/apixu.rb
require_relative '../demo_base' class APIXU < TLAW::API define do docs 'https://www.apixu.com/doc/' base 'http://api.apixu.com/v1' param :key, required: true param :lang namespace :current, '/current.json' do endpoint :city, '?q={city}' do param :city, :to_s, required: true end end namespace :forecast, '/forecast.json' do endpoint :city, '?q={city}' do param :city, :to_s, required: true param :days, :to_i param :dt, Date, format: ->(dt) { dt.strftime('%Y-%m-%d') } end end end end apixu = APIXU.new(key: ENV['APIXU'], lang: 'uk') pp apixu.current.city('Kharkiv') #res = apixu.forecast.city('Odesa', days: 10, dt: Date.parse('2017-07-03')) #pp res['forecast.forecastday']['day.mintemp_c'] #pp res['forecast.forecastday']['day.maxtemp_c']
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/wunderground.rb
examples/experimental/wunderground.rb
module TLAW module Examples class WUnderground < TLAW::API define do base 'http://api.wunderground.com/api/{api_key}{/features}{/lang}/q' param :api_key, required: true param :lang, format: 'lang:#%s'.method(:%) FEATURES = %i[ alerts almanac astronomy conditions currenthurricane forecast forecast10day geolookup hourly hourly10day rawtide tide webcams yesterday ].freeze ALL_FEATURES = %i[ history planner ] shared_def :common_params do param :features, Array, format: ->(a) { a.join('/') } #TODO: enum: FEATURES -- doesn't work with Array param :pws, enum: {false => 0, true => 1} param :bestfct, enum: {false => 0, true => 1} end post_process { |h| h.key?('response.error.type') and fail h['response.error.type'] } endpoint :city, '{/country}/{city}.json' do param :city, required: true use_def :common_params end endpoint :us_zipcode do end endpoint :location do end endpoint :airport do end endpoint :pws do end endpoint :geo_ip do end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/open_exchange_rates.rb
examples/experimental/open_exchange_rates.rb
require_relative '../demo_base' class OpenExchangeRate < TLAW::API define do base 'https://openexchangerates.org/api' param :app_id, required: true post_process { |h| h['rates'] = h .select { |k, v| k.start_with?('rates.') } .map { |k, v| {'to' => k.sub('rates.', ''), 'rate' => v} } h.reject! { |k, v| k.start_with?('rates.') } } post_process 'timestamp', &Time.method(:at) endpoint :currencies, path: '/currencies.json' endpoint :latest, path: '/latest.json' endpoint :historical, path: '/historical/{date}.json' do param :date, :to_date, format: ->(v) { v.strftime('%Y-%m-%d') } end endpoint :usage, path: '/usage.json' end end api = OpenExchangeRate.new(app_id: ENV['OPEN_EXCHANGE_RATES']) #pp api.latest['rates'].first(3) #pp api.historical(Date.parse('2016-05-01'))['rates'].detect { |r| r['to'] == 'INR' } #, base: 'USD') #pp api.convert(100, 'INR', 'USD') #pp api.usage pp api.latest['rates'].detect { |r| r['to'] == 'INR' }
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/reddit.rb
examples/experimental/reddit.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class Reddit < TLAW::API define do base 'https://www.reddit.com' post_process_items 'data.children' do post_process("data.permalink") { |v| "https://www.reddit.com#{v}" } post_process("data.created", &Time.method(:at)) end namespace :r, '/r/{subreddit}' do endpoint :new, '/new.json' do end end end end r = Reddit.new res = r.r(:ruby).new p res['data.children']['data.ups'] p res['data.children']['data.num_comments']
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/omdb.rb
examples/experimental/omdb.rb
require_relative '../demo_base' #http://docs.themoviedb.apiary.io/#reference/movies/movielatest class OMDB < TLAW::API define do base 'http://www.omdbapi.com' param :api_key, field: :apikey, required: true SPLIT = ->(v) { v.split(/\s*,\s*/) } shared_def :imdb do post_process('imdbRating', &:to_f) post_process('imdbVotes') { |v| v.gsub(',', '').to_i } end post_process do |response| response.delete('Response') == 'False' and fail(response['Error']) end endpoint :by_id, path: '/?i={imdb_id}' do param :imdb_id, required: true param :type, enum: %i[movie series episode] param :year, :to_i, field: :y param :plot, enum: %i[short full] param :tomatoes, enum: [true, false] post_process('Released', &Date.method(:parse)) post_process('totalSeasons', &:to_i) use_def :imdb end endpoint :by_title, path: '/?t={title}' do param :title, required: true param :type, enum: %i[movie series episode] param :year, :to_i, field: :y param :plot, enum: %i[short full] param :tomatoes, enum: [true, false] post_process('Released', &Date.method(:parse)) use_def :imdb post_process('Metascore', &:to_i) post_process('totalSeasons', &:to_i) post_process('Genre', &SPLIT) post_process('Country', &SPLIT) post_process('Writer', &SPLIT) post_process('Actors', &SPLIT) end endpoint :search, path: '/?s={search}' do param :search, required: true param :type, enum: %i[movie series episode] param :year, :to_i, field: :y param :page, :to_i end end end o = OMDB.new(api_key: ENV.fetch('OMDB')) #pp o.by_id("tt0944947") pp o.by_title('Suicide Squad', tomatoes: true, plot: :full) #pp o.search('Game of')['Search'].first
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/world_bank_climate.rb
examples/experimental/world_bank_climate.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class WorldBankClimate < TLAW::API define do base 'http://climatedataapi.worldbank.org/climateweb/rest/v1' { basin: :basinID, country: :country_iso3 }.each do |namespace_name, param_name| namespace namespace_name do param param_name, keyword: false, required: true { :temperature => 'tas', :precipation => 'pr' }.each do |varname, var| namespace varname, path: '' do { monthly: 'mavg', annual: 'annualavg', monthly_anomaly: 'manom', annual_anomaly: 'annualanom' }.each do |typename, type| endpoint typename, path: "/#{type}/#{var}/{since}/{#{param_name}}.json" do param :since, keyword: true, required: true, enum: { 1920 => '1920/1939', 1940 => '1940/1959', 1960 => '1960/1979', 1980 => '1980/1999', 2020 => '2020/2039', 2040 => '2040/2059', 2060 => '2060/2079', 2080 => '2080/2099', } if typename.to_s.include?('monthly') post_process_replace do |res| { 'variable' => res.first['variable'], 'fromYear' => res.first['fromYear'], 'toYear' => res.first['toYear'], 'data' => TLAW::DataTable .from_columns( res.map { |r| r['gcm'] }, res.map { |r| r['monthVals'] } ) } end else post_process_replace do |res| { 'variable' => res.first['variable'], 'fromYear' => res.first['fromYear'], 'toYear' => res.first['toYear'], 'gcm' => res.map { |res| [res['gcm'], res['annualData'].first] }.to_h } end end end end end end end end end end wbc = WorldBankClimate.new pp wbc.country('ukr').temperature.annual(since: 1980) pp wbc.country('ukr').precipation.monthly(since: 1980)['data']
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/swapi.rb
examples/experimental/swapi.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class SWAPI < TLAW::API define do base 'http://swapi.co/api' namespace :people do endpoint :all, '' endpoint :[], '/{id}/' endpoint :search, '/?search={query}' end namespace :species do endpoint :all, '' endpoint :[], '/{id}/' endpoint :search, '/?search={query}' end end end s = SWAPI.new pp s.people.search('r2')['results'].first pp s.species[2]
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/musicbrainz.rb
examples/experimental/musicbrainz.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class MusicBrainz < TLAW::API define do base 'http://musicbrainz.org/ws/2' endpoint :area, '/area/{id}?fmt=json' namespace :artist do endpoint :area, '?area={area_id}&fmt=json' endpoint :get, '/{id}?fmt=json' do param :inc, :to_a, format: ->(a) { a.join('+') } end end end end mb = MusicBrainz.new #pp mb.area '37572420-4b2c-47e5-bf2b-536c9a50a362' #pp mb.artist.area('904768d0-61ca-3c40-93ac-93adc36fef4b')['artists'].first res = mb.artist.get('00496bc8-93bf-4284-a3ea-cfd97eb99b2f', inc: %w[recordings releases release-groups works]) pp res['recordings'].first pp res['releases'].first
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/currencylayer.rb
examples/experimental/currencylayer.rb
require_relative '../demo_base' class CurrencyLayer < TLAW::API define do base 'http://apilayer.net/api/' param :access_key, required: true endpoint :live do param :currencies, Array end endpoint :historical do param :date, :to_date, required: :true, keyword: false, format: ->(d) { d.strftime('%Y-%m-%d') } param :currencies, Array post_process 'date', &Date.method(:parse) post_process 'timestamp', &Time.method(:at) end end end cur = CurrencyLayer.new(access_key: ENV['CURRENCYLAYER']) pp cur.historical(Date.parse('2016-01-01'), currencies: %w[UAH])
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/freegeoip.rb
examples/experimental/freegeoip.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class FreeGeoIP < TLAW::API define do base 'http://freegeoip.net/json/' endpoint :here, '' endpoint :at, '/{ip}' end end fgi = FreeGeoIP.new pp fgi.here
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/isfdb.rb
examples/experimental/isfdb.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class ISFDB < TLAW::API define do base 'http://www.isfdb.org/cgi-bin/rest' endpoint :isbn, '/getpub.cgi?{isbn}', xml: true end end i = ISFDB.new #pp i.isbn('0399137378')["ISFDB.Publications.Publication"].last pp i.isbn('038533348X')["ISFDB.Publications.Publication"].to_a
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/earthquake.rb
examples/experimental/earthquake.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class Earthquake < TLAW::API define do base 'http://earthquake.usgs.gov/fdsnws/event/1' endpoint :count, '/count?format=geojson' do param :starttime, Date, format: ->(d) { d.strftime('%Y-%m-%d') } param :endtime, Date, format: ->(d) { d.strftime('%Y-%m-%d') } end endpoint :query, '/query?format=geojson' do param :starttime, Date, format: ->(d) { d.strftime('%Y-%m-%d') } param :endtime, Date, format: ->(d) { d.strftime('%Y-%m-%d') } param :minmagnitude, :to_i end end end #/query?format=geojson&starttime=2001-01-01&endtime=2014-01-02 e = Earthquake.new res = e.query(starttime: Date.parse('2000-01-01'), endtime: Date.parse('2017-01-02'), minmagnitude: 9) pp res['features'].count pp res['features'].first
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/wunderground_demo.rb
examples/experimental/wunderground_demo.rb
#!/usr/bin/env ruby require_relative '../demo_base' require_relative 'wunderground' weather = TLAW::Examples::WUnderground.new(api_key: ENV['WUNDERGROUND']) pp weather.city('Kharkiv', 'Ukraine', features: %i[astronomy tide])
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/open_street_map.rb
examples/experimental/open_street_map.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class OpenStreetMap < TLAW::API define do base 'http://api.openstreetmap.org/api/0.6' endpoint :relation, '/relation/{id}', xml: true end end osm = OpenStreetMap.new pp osm.relation(1543125)["osm.relation.tag"].to_a
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/nominatim.rb
examples/experimental/nominatim.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class Nominatim < TLAW::API define do base 'http://nominatim.openstreetmap.org' param :lang, field: 'accept%2Dlanguage' namespace :search, '/search?format=json' do endpoint :query, '' do param :query, field: :q, keyword: false param :details, field: :addressdetails, enum: {false => 0, true => 1} param :geojson, field: :polygon_geojson, enum: {false => 0, true => 1} param :tags, field: :extratags, enum: {false => 0, true => 1} param :limit end endpoint :address, '' do param :city param :country param :street param :postalcode param :details, field: :addressdetails, enum: {false => 0, true => 1} param :geojson, field: :polygon_geojson, enum: {false => 0, true => 1} param :tags, field: :extratags, enum: {false => 0, true => 1} end end endpoint :geocode, '/reverse?format=json' do param :lat, :to_f, keyword: false param :lng, :to_f, field: :lon, keyword: false end endpoint :lookup, '/lookup?format=json&osm_ids={ids}' do param :ids # , splat: true -- TODO end end end n = Nominatim.new(lang: 'en') #pp n.search.address(country: 'Ukraine', city: 'Kharkiv', street: '33a Oleksiivska', details: true, geojson: true, tags: true).first # pp n.search.query('New York, Times Square', details: true, tags: true, limit: 1).to_a #pp n.geocode(50.0403843, 36.203339684) #pp n.search.query('Pharmacy, Kharkiv', details: true, tags: true, limit: 100)['address.pharmacy'].compact #pp n.geocode(49.9808, 36.2527) # pp n.search.address(country: 'Thailand', city: 'Bangkok', details: true, tags: true).to_a pp n.search.query('Oleksiivska 33a, Kharkiv, Ukraine').to_a
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/world_bank.rb
examples/experimental/world_bank.rb
require 'pp' $:.unshift 'lib' require 'tlaw' class WorldBank < TLAW::API define do base 'http://api.worldbank.org' post_process_replace { |response| if response.is_a?(Array) && response.size == 1 && response.first.is_a?(Hash) response.first elsif response.is_a?(Array) && response.size == 2 {'meta' => response.first, 'data' => response.last} else response end } post_process_items('data') do post_process 'longitude', &:to_f post_process 'latitude', &:to_f post_process 'value', &:to_f # post_process 'date', &Date.method(:parse) end SINGULAR = ->(h) { h['data'].first } namespace :countries, '/countries' do endpoint :list, '?format=json' do param :income_level, field: :incomeLevel param :lending_type, field: :lendingType end namespace :[], '/{country}' do #param :countries, :to_a, format: ->(c) { c.join(';') } # TODO: splat endpoint :get, '?format=json' do #post_process_replace(&SINGULAR) end endpoint :indicator, '/indicators/{name}?format=json' # TODO: filter indicator by date end end namespace :dictionaries, '' do endpoint :topics, '/topics?format=json' #namespace :sources, '/sources?format=json' do endpoint :income_levels, '/incomeLevels?format=json' endpoint :lending_types, '/lendingTypes?format=json' namespace :indicators do endpoint :list, '?format=json' endpoint :by_topic, '/../topic/{topic_id}/indicator?format=json' endpoint :by_source, '/../source/{source_id}/indicators?format=json' endpoint :[], '/{name}?format=json' do post_process_replace(&SINGULAR) end end end end end wb = WorldBank.new #pp wb.dictionaries.indicators.list #pp wb.sources['data']['name'].reject(&:empty?) #pp wb.countries(income_level: 'LIC')['data']['name'].sort # ['message'].first #pp wb.indicators['NY.GDP.MKTP.CD'] #['data'].first #pp wb.sources[3].indicators #['data']['name'] #pp wb.countries['ua'].indicator('NY.GDP.MKTP.CD')['data'].first(5) #pp wb.countries['ua'].get #pp wb.dictionaries.indicators.by_topic(5)['data'].last #pp wb.countries.list['data'].to_a #pp wb.countries['us'].indicator("EG.EGY.PRIM.PP.KD")['data'].first(10) #pp wb.countries['ukr'].get['data'].first #pp wb.dictionaries.indicators.list pp wb.countries['ukr'].indicator('SP.POP.TOTL')['data'].to_a.first(3)
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/afterthedeadline.rb
examples/experimental/afterthedeadline.rb
require 'pp' $:.unshift 'lib' require 'tlaw' #http://docs.themoviedb.apiary.io/#reference/movies/movielatest class AfterTheDeadline < TLAW::API define do base 'http://service.afterthedeadline.com' param :key, required: true endpoint :document, '/checkDocument', xml: true do param :data, keyword: false end end end atd = AfterTheDeadline.new(key: 'test-tlaw') pp atd.document("Isn't it cool and cute and awesme? Yepx it is.")['results.error'].to_a
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/examples/experimental/geonames.rb
examples/experimental/geonames.rb
require_relative '../demo_base' require 'geo/coord' #http://www.geonames.org/export/web-services.html #http://www.geonames.org/export/credits.html #http://www.geonames.org/export/ws-overview.html class GeoNames < TLAW::API define do base 'http://api.geonames.org' param :username, required: true param :lang ERROR_CODES = { 10 => 'Authorization Exception', 11 => 'record does not exist', 12 => 'other error', 13 => 'database timeout', 14 => 'invalid parameter', 15 => 'no result found', 16 => 'duplicate exception', 17 => 'postal code not found', 18 => 'daily limit of credits exceeded', 19 => 'hourly limit of credits exceeded', 20 => 'weekly limit of credits exceeded', 21 => 'invalid input', 22 => 'server overloaded exception', 23 => 'service not implemented', } post_process do |response| if response['status.value'] fail "#{ERROR_CODES[response['status.value']]}: #{response['status.message']}" end end namespace :search, path: '/searchJSON' do endpoint :query, path: '?q={q}' do param :q, required: true param :country #TODO: country=FR&country=GP end endpoint :name, path: '?name={name}' do param :name, required: true end endpoint :name_equals, path: '?name_equals={name}' do param :name, required: true end end namespace :postal_codes, path: '' do endpoint :countries, path: '/postalCodeCountryInfoJSON' end namespace :near, path: '' do param :lat, keyword: false param :lng, keyword: false endpoint :ocean, path: '/oceanJSON' endpoint :country, path: '/countryCodeJSON' endpoint :weather, path: '/findNearByWeatherJSON' endpoint :extended, path: '/extendedFindNearby', xml: true do post_process_replace { |res| res['geonames.geoname'] } end end namespace :weather, path: '' do endpoint :near, path: '/findNearByWeatherJSON?lat={lat}&lng={lng}' end endpoint :earthquakes, path: '/earthquakesJSON' do param :north param :south param :east param :west post_process_items 'earthquakes' do post_process 'datetime', &Time.method(:parse) post_process { |h| h['coord'] = Geo::Coord.new(h['lat'], h['lng']) } end end end end gn = GeoNames.new(username: ENV.fetch('GEONAMES')) #pp gn.search.name_equals('Kharkiv')['geonames'].to_a #pp gn.postal_codes.countries['geonames'].detect { |r| r['countryName'].include?('Thai') } #pp gn.near(50.004444, 36.231389).country #pp gn.near(50.004444, 36.231389).ocean pp gn.near(50.004444, 36.231389).extended.to_a #pp gn.near(50.004444, 36.231389).weather #pp gn.weather.near(50.004444, 36.231389) #pp gn.earthquakes(north: 44.1, south: -9.9, east: -22.4, west: 55.2)['earthquakes'].to_a # => to worldize!
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw.rb
lib/tlaw.rb
# frozen_string_literal: true require 'json' require 'backports/2.4.0/string/match' require 'backports/2.4.0/hash/compact' require 'backports/2.4.0/hash/transform_values' require 'backports/2.5.0/kernel/yield_self' require 'backports/2.5.0/hash/transform_keys' require 'backports/2.5.0/enumerable/all' require 'addressable/uri' require 'addressable/template' # TLAW is a framework for creating API wrappers for get-only APIs (like # weather, geonames and so on) or subsets of APIs (like getting data from # Twitter). # # Short example: # # ```ruby # # Definition: # class OpenWeatherMap < TLAW::API # param :appid, required: true # # namespace :current, '/weather' do # endpoint :city, '?q={city}{,country_code}' do # param :city, required: true # end # end # end # # # Usage: # api = OpenWeatherMap.new(appid: '<yourappid>') # api.current.weather('Kharkiv') # # => {"weather.main"=>"Clear", # # "weather.description"=>"clear sky", # # "main.temp"=>8, # # "main.pressure"=>1016, # # "main.humidity"=>81, # # "dt"=>2016-09-19 08:30:00 +0300, # # ...} # # ``` # # Refer to [README](./file/README.md) for reasoning about why you need it and links to # more detailed demos, or start reading YARD docs from {API} and {DSL} # modules. module TLAW end require_relative 'tlaw/util' require_relative 'tlaw/data_table' require_relative 'tlaw/param' require_relative 'tlaw/api_path' require_relative 'tlaw/endpoint' require_relative 'tlaw/namespace' require_relative 'tlaw/api' require_relative 'tlaw/formatting' require_relative 'tlaw/response_processors' require_relative 'tlaw/dsl'
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/response_processors.rb
lib/tlaw/response_processors.rb
# frozen_string_literal: true module TLAW # @private module ResponseProcessors # @private module Generators module_function def mutate(&block) proc { |hash| hash.tap(&block) } end def transform_by_key(key_pattern, &block) proc { |hash| ResponseProcessors.transform_by_key(hash, key_pattern, &block) } end def transform_nested(key_pattern, nested_key_pattern = nil, &block) transformer = if nested_key_pattern transform_by_key(nested_key_pattern, &block) else mutate(&block) end proc { |hash| ResponseProcessors.transform_nested(hash, key_pattern, &transformer) } end end class << self def transform_by_key(value, key_pattern) return value unless value.is_a?(Hash) value .map { |k, v| key_pattern === k ? [k, yield(v)] : [k, v] } # rubocop:disable Style/CaseEquality .to_h end def transform_nested(value, key_pattern, &block) transform_by_key(value, key_pattern) { |v| v.is_a?(Array) ? v.map(&block) : v } end def flatten(value) case value when Hash flatten_hash(value) when Array value.map(&method(:flatten)) else value end end def datablize(value) case value when Hash value.transform_values(&method(:datablize)) when Array if !value.empty? && value.all?(Hash) DataTable.new(value) else value end else value end end private def flatten_hash(hash) hash.flat_map do |k, v| v = flatten(v) if v.is_a?(Hash) v.map { |k1, v1| ["#{k}.#{k1}", v1] } else [[k, v]] end end.reject { |_, v| v.nil? }.to_h end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/version.rb
lib/tlaw/version.rb
# frozen_string_literal: true module TLAW MAJOR = 0 MINOR = 1 PATCH = 0 PRE = 'pre' VERSION = [MAJOR, MINOR, PATCH, PRE].compact.join('.') end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/namespace.rb
lib/tlaw/namespace.rb
# frozen_string_literal: true module TLAW # Namespace is a grouping tool for API endpoints. # # Assuming we have this API definition: # # ```ruby # class OpenWeatherMap < TLAW::API # define do # base 'http://api.openweathermap.org/data/2.5' # # namespace :current, '/weather' do # endpoint :city, '?q={city}{,country_code}' # end # end # end # ``` # # We can now use it this way: # # ```ruby # api = OpenWeatherMap.new # api.namespaces # # => [OpenWeatherMap::Current(call-sequence: current; endpoints: city; docs: .describe)] # api.current # # => #<OpenWeatherMap::Current(); endpoints: city; docs: .describe> # # OpenWeatherMap::Current is dynamically generated class, descendant from Namespace, # # it is inspectable and usable for future calls # # api.current.describe # # current # # # # Endpoints: # # # # .city(city=nil, country_code=nil) # # api.current.city('Kharkiv', 'UA') # # => real API call at /weather?q=Kharkiv,UA # ``` # # Namespaces are useful for logical endpoint grouping and allow providing additional params to # them. When params are defined for namespace by DSL, the call could look like this: # # ```ruby # worldbank.countries('uk').population(2016) # # ^^^^^^^^^^^^^^ ^ # # namespace :countries have | # # defined country_code parameter | # # all namespace and endpoint params would be passed to endpoint call, # # so real API call would probably look like ...?country=uk&year=2016 # ``` # # See {DSL} for more details on namespaces, endpoints and params definitions. # class Namespace < APIPath class << self # @private TRAVERSE_RESTRICTION = { endpoints: Endpoint, namespaces: Namespace, nil => APIPath }.freeze # Traverses through all of the children (depth-first). Yields them into a block specified, # or returns `Enumerator` if no block was passed. # # @yield [Namespace or Endpoint] # @param restrict_to [Symbol] `:endpoints` or `:namespaces` to traverse only children of # specified class; if not passed, traverses all of them. # @return [Enumerator, self] Enumerator is returned if no block passed. def traverse(restrict_to = nil, &block) return to_enum(:traverse, restrict_to) unless block_given? klass = TRAVERSE_RESTRICTION.fetch(restrict_to) children.each do |child| yield child if child < klass child.traverse(restrict_to, &block) if child.respond_to?(:traverse) end self end # Returns the namespace's child of the requested name. # # @param name [Symbol] # @param restrict_to [Class] `Namespace` or `Endpoint` # @return [Array<APIPath>] def child(name, restrict_to: APIPath) child_index[name] .tap { |child| validate_class(name, child, restrict_to) } end # Lists all current namespace's nested namespaces. # # @return [Array<Namespace>] def namespaces children.grep(Namespace.singleton_class) end # Returns the namespace's nested namespaces of the requested name. # # @param name [Symbol] # @return [Namespace] def namespace(name) child(name, restrict_to: Namespace) end # Lists all current namespace's endpoints. # # @return [Array<Endpoint>] def endpoints children.grep(Endpoint.singleton_class) end # Returns the namespace's endpoint of the requested name. # # @param name [Symbol] # @return [Endpoint] def endpoint(name) child(name, restrict_to: Endpoint) end # @return [String] def inspect return super unless is_defined? || self < API Formatting::Inspect.namespace_class(self) end # Detailed namespace documentation. # # @return [Formatting::Description] def describe return '' unless is_defined? Formatting::Describe.namespace_class(self) end # @private def definition super.merge(children: children) end # @private def children child_index.values end # @private def child_index @child_index ||= {} end protected def setup(children: [], **args) super(**args) self.children = children.dup.each { |c| c.parent = self } end def children=(children) children.each do |child| child_index[child.symbol] = child end end private def validate_class(sym, child_class, expected_class) return if child_class&.<(expected_class) kind = expected_class.name.split('::').last.downcase.sub('apipath', 'path') fail ArgumentError, "Unregistered #{kind}: #{sym}" end end def_delegators :self_class, :symbol, :namespaces, :endpoints, :namespace, :endpoint # @return [String] def inspect Formatting::Inspect.namespace(self) end # Returns `curl` string to call specified endpoit with specified params from command line. # # @param endpoint [Symbol] Endpoint's name # @param params [Hash] Endpoint's argument # @return [String] def curl(endpoint, **params) child(endpoint, Endpoint, **params).to_curl end private def child(sym, expected_class, **params) self.class.child(sym, restrict_to: expected_class).new(self, **params) end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/formatting.rb
lib/tlaw/formatting.rb
# frozen_string_literal: true module TLAW # Just a bit of formatting utils. module Formatting # Description is just a String subclass with rewritten `inspect` # implementation (useful in `irb`/`pry`): # # ```ruby # str = "Description of endpoint:\nIt has params:..." # # "Description of endpoint:\nIt has params:..." # # TLAW::Formatting::Description.new(str) # # Description of endpoint: # # It has params:... # ``` # # TLAW uses it when responds to {Namespace.describe}/{Endpoint.describe}. # class Description < String alias inspect to_s def initialize(str) super(str.to_s.gsub(/ +\n/, "\n")) end end module_function # @private def call_sequence(klass) params = params_to_ruby(klass.param_defs) name = klass < API ? "#{klass.name}.new" : klass.symbol.to_s params.empty? ? name : "#{name}(#{params})" end # @private def params_to_ruby(params) # rubocop:disable Metrics/AbcSize key, arg = params.partition(&:keyword?) req_arg, opt_arg = arg.partition(&:required?) req_key, opt_key = key.partition(&:required?) # FIXME: default.inspect will fail with, say, Time [ *req_arg.map { |p| p.name.to_s }, *opt_arg.map { |p| "#{p.name}=#{p.default.inspect}" }, *req_key.map { |p| "#{p.name}:" }, *opt_key.map { |p| "#{p.name}: #{p.default.inspect}" } ].join(', ') end end end require_relative 'formatting/inspect' require_relative 'formatting/describe'
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/param.rb
lib/tlaw/param.rb
# frozen_string_literal: true require_relative 'param/type' module TLAW # @private class Param attr_reader :name, :field, :type, :description, :default, :format def initialize( name:, field: name, type: nil, description: nil, required: false, keyword: true, default: nil, format: :itself ) @name = name @field = field @type = Type.coerce(type) @description = description @required = required @keyword = keyword @default = default @format = format end def to_h { name: name, field: field, type: type, description: description, required: required?, keyword: keyword?, default: default, format: format } end def required? @required end def keyword? @keyword end def call(value) type.(value) .yield_self(&format) .yield_self { |val| {field => Array(val).join(',')} } rescue TypeError => e raise TypeError, "#{name}: #{e.message}" end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/api.rb
lib/tlaw/api.rb
# frozen_string_literal: true module TLAW # API is a main TLAW class (and the only one you need to use directly). # # Basically, you start creating your definition by descending from API and defining namespaces and # endpoints through a {DSL} like this: # # ```ruby # class SomeImagesAPI < TLAW::API # define do # base 'http://api.mycool.com' # # namespace :gifs do # endpoint :search do # param :query # end # # ...and so on # end # end # end # ``` # # And then, you use it: # # ```ruby # api = SomeImagesAPI.new # api.gifs.search(query: 'butterfly') # ``` # # See {DSL} for detailed information of API definition, and {Namespace} for explanation about # dynamically generated methods ({API} is also an instance of a {Namespace}). # class API < Namespace # Thrown when there are an error during call. Contains real URL which was called at the time of # an error. class Error < RuntimeError end class << self # @private attr_reader :url_template # Runs the {DSL} inside your API wrapper class. def define(&block) self == API and fail '#define should be called on the descendant of the TLAW::API' DSL::ApiBuilder.new(self, &block).finalize self end # @private def setup(base_url: nil, **args) if url_template base_url and fail ArgumentError, "API's base_url can't be changed on redefinition" else base_url or fail ArgumentError, "API can't be defined without base_url" self.url_template = base_url end super(symbol: nil, path: '', **args) end # @private def is_defined? # rubocop:disable Naming/PredicateName self < API end protected attr_writer :url_template private :parent, :parent= end private :parent # Create an instance of your API descendant. # Params to pass here correspond to `param`s defined at top level of the DSL, e.g. # # ```ruby # # if you defined your API like this... # class MyAPI < TLAW::API # define do # param :api_key # # .... # end # end # # # the instance should be created like this: # api = MyAPI.new(api_key: '<some-api-key>') # ``` # # If the block is passed, it is called with an instance of # [Faraday::Connection](https://www.rubydoc.info/gems/faraday/Faraday/Connection) object which # would be used for API requests, allowing to set up some connection configuration: # # ```ruby # api = MyAPI.new(api_key: '<some-api-key>') { |conn| conn.basic_auth 'login', 'pass' } # ``` # # @yield [Faraday::Connection] def initialize(**params, &block) super(nil, **params) @client = Faraday.new do |faraday| faraday.use FaradayMiddleware::FollowRedirects faraday.adapter Faraday.default_adapter block&.call(faraday) end end # @private def request(url, **params) @client.get(url, **params).tap(&method(:guard_errors!)) rescue Error raise # Not catching in the next block rescue StandardError => e raise Error, "#{e.class} at #{url}: #{e.message}" end private def guard_errors!(response) # TODO: follow redirects return response if (200...400).cover?(response.status) fail Error, "HTTP #{response.status} at #{response.env[:url]}" + extract_message(response.body)&.yield_self { |m| ': ' + m }.to_s end def extract_message(body) # FIXME: well, that's just awful # ...minimal is at least extract *_message key (TMDB has status_message, for ex.) data = JSON.parse(body) rescue nil return body unless data.is_a?(Hash) data.values_at('message', 'error').compact.first || body end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/dsl.rb
lib/tlaw/dsl.rb
# frozen_string_literal: true module TLAW # This module is core of a TLAW API definition. It works like this: # # ```ruby # class MyAPI < TLAW::API # define do # here starts what DSL does # namespace :ns do # # endpoint :es do # param :param1, Integer, default: 1 # end # end # end # end # ``` # # Methods of current namespace documentation describe everything you # can use inside `define` blocks. Actual structure of things is a bit # more complicated (relate to lib/tlaw/dsl.rb if you wish), but current # documentation structure considered to be most informative. # module DSL # @!method base(url) # Set entire API base URL, all endpoints and namespaces pathes are calculated relative to it. # # **Works for:** API # # @param url [String] # @!method desc(text) # Set description string for API object (namespace or endpoint). It can be multiline, and # TLAW will automatically un-indent excessive indentations: # # ```ruby # # ...several levels of indents while you create a definition # desc %Q{ # This is some endpoint. # And it works! # } # # # ...but when you are using it... # p my_api.endpoint(:endpoint).describe # # This is some endpoint. # # And it works! # # .... # ``` # # **Works for:** API, namespace, endpoint # # @param text [String] # @!method docs(link) # Add link to documentation as a separate line to object description. Just to be semantic :) # # ```ruby # # you do something like # desc "That's my endpoint" # # docs "http://docs.example.com/my/endpoint" # # # ...and then somewhere... # p my_api.endpoint(:endpoint).describe # # That is my endpoint. # # # # Docs: http://docs.example.com/my/endpoint # # .... # ``` # # **Works for:** API, namespace, endpoint # # @param link [String] # @!method param(name, type = nil, keyword: true, required: false, **opts) # Defines parameter for current API (global), namespace or endpoint. # # Param defnition defines several things: # # * how method definition to call this namespace/endpoint would look like: whether the # parameter is keyword or regular argument, whether it is required and what is default # value otherwise; # * how parameter is processed: converted and validated from passed value; # * how param is sent to target API: how it will be called in the query string and formatted # on call. # # Note also those things about params: # # * as described in {#namespace} and {#endpoint}, setting path template will implicitly set # params. You can rewrite this on implicit param call, for ex: # # ```ruby # endpoint :foo, '/foo/{bar}' # # call-sequence would be foo(bar = nil) # # # But you can make it back keyword: # endpoint :foo, '/foo/{bar}' do # param :bar, keyword: true, default: 'test' # end # # call-sequence now is foo(bar: 'test') # # # Or make it strictly required # endpoint :foo, '/foo/{bar}/{baz}' do # param :bar, required: true # param :baz, keyword: true, required: true # end # # call-sequence now is foo(bar, baz:) # ``` # # * param of outer namespace are passed to API on call to inner namespaces and endpoints, for ex: # # ```ruby # namespace :city do # param :city_name # # namespace :population do # endpoint :by_year, '/year/{year}' # end # end # # # real call: # api.city('London').population.by_year(2015) # # Will get http://api.example.com/city/year/2015?city_name=London # ``` # # **Works for:** API, namespace, endpoint # # @param name [Symbol] Parameter name # @param type [Class, Symbol] Expected parameter type. Could by some class (then parameter # would be checked for being instance of this class or it would be `ArgumentError`), or # duck type (method name that parameter value should respond to). # @param keyword [true, false] Whether the param will go as a keyword param to method definition. # @param required [true, false] Whether this param is required. It will be considered on # method definition. # @param opts [Hash] Options # @option opts [Symbol] :field What the field would be called in API query string (it would be # param's name by default). # @option opts [#to_proc] :format How to format this option before including into URL. By # default, it is just `.to_s`. # @option opts [String] :desc Params::Base description. You could do it multiline and with # indents, like {#desc}. # @option opts :default Default value for this param. Would be rendered in method definition # and then passed to target API _(TODO: in future, there also would be "invisible" params, # that are just passed to target, always the same, as well as params that aren't passed at # all if user gave default value.)_ # @option opts [Hash, Array] :enum Whether parameter only accepts enumerated values. Two forms # are accepted: # # ```ruby # # Enumerable form # param :units, enum: %i[us metric britain] # # parameter accepts only :us, :metric, :britain values, and passes them to target API as is # # any Enumerable is OK: # param :count, enum: 1..5 # # ^ note that means [1, 2, 3, 4, 5], not "any Numeric between 1 and 5" # # # hash "accepted => passed" form # param :compact, enum: {true => 'gzip', false => nil} # # parameter accepts true or false, on true passes "compact=gzip", on false passes nothing. # ``` # @!method namespace(name, path = nil, &block) # Defines new namespace or updates existing one. # # {Namespace} has two roles: # # * on Ruby API, defines how you access to the final endpoint, like # `api.namespace1.namespace2(some_param).endpoint(...)` # * on calling API, it adds its path to entire URL. # # **NB:** If you call `namespace(:something)` and it was already defined, current definition # will be added to existing one (but it can't change path of existing one, which is reasonable). # # **Works for:** API, namespace # # @param name [Symbol] Name of the method by which namespace would be accessible. # @param path [String] Path to add to API inside this namespace. # When not provided, considered to be `/<name>`. When provided, taken literally (no slashes # or other symbols added). Note, that you can use `/../` in path, redesigning someone else's # APIs on the fly. Also, you can use [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570.txt) # URL templates to mark params going straightly into URI. # # Some examples: # # ```ruby # # assuming API base url is http://api.example.com # # namespace :foo # # method would be foo(), API URL would be http://api.example.com/foo # # namespace :bar, '/foo/bar' # # metod would be bar(), API URL http://api.example.com/foo/bar # # namespace :baz, '' # # method baz(), API URL same as base: useful for gathering into # # quazi-namespace from several unrelated endpoints. # # namespace :quux, '/foo/quux/{id}' # # method quux(id = nil), API URL http://api.example.com/foo/quux/123 # # ...where 123 is what you've passed as id # ``` # @param block Definition of current namespace params, and namespaces and endpoints inside # current. Note that by defining params inside this block, you can change namespace's method # call sequence. # # For example: # # ```ruby # namespace :foo # # call-sequence: foo() # # namespace :foo do # param :bar # end # # call-sequence: foo(bar: nil) # # namespace :foo do # param :bar, required: true, keyword: false # param :baz, required: true # end # # call-sequence: foo(bar, baz:) # ``` # # ...and so on. See also {#param} for understanding what you can change here. # @!method endpoint(name, path = nil, **opts, &block) # Defines new endpoint or updates existing one. # # {Endpoint} is the thing doing the real work: providing Ruby API method to really call target # API. # # **NB:** If you call `endpoint(:something)` and it was already defined, current definition # will be added to existing one (but it can't change path of existing one, which is reasonable). # # **Works for:** API, namespace # # @param name [Symbol] Name of the method by which endpoint would be accessible. # @param path [String] Path to call API from this endpoint. # When not provided, considered to be `/<name>`. When provided, taken literally (no slashes # or other symbols added). Note, that you can use `/../` in path, redesigning someone else's # APIs on the fly. Also, you can use [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570.txt) # URL templates to mark params going straightly into URI. # # Look at {#namespace} for examples, idea is the same. # # @param opts [Hash] Some options, currently only `:xml`. # @option opts [true, false] :xml Whether endpoint's response should be parsed as XML (JSON # otherwise & by default). Parsing in this case is performed with # [crack](https://github.com/jnunemaker/crack), producing the hash, to which all other rules # of post-processing are applied. # @param block Definition of endpoint's params and docs. Note that by defining params inside # this block, you can change endpoints's method call sequence. # # For example: # # ```ruby # endpoint :foo # # call-sequence: foo() # # endpoint :foo do # param :bar # end # # call-sequence: foo(bar: nil) # # endpoint :foo do # param :bar, required: true, keyword: false # param :baz, required: true # end # # call-sequence: foo(bar, baz:) # ``` # # ...and so on. See also {#param} for understanding what you can change here. # @!method post_process(key = nil, &block) # Sets post-processors for response. # # There are also {#post_process_replace} (for replacing entire response with something else) # and {#post_process_items} (for post-processing each item of sub-array). # # Notes: # # * You can set any number of post-processors of any kind, and they will be applied in exactly # the same order they are set. # * You can set post-processors in parent namespace (or for entire API), in this case # post-processors of _outer_ namespace are always applied before inner ones. That allow you # to define some generic parsing/rewriting on API level, then more specific key # postprocessors on endpoints. But only post-processors defined BEFORE the nested object # definition would be taken into account. # * Hashes are flattened again after _each_ post-processor, so if for some `key` you'll # return `{count: 1, continue: false}`, response hash will immediately have # `{"key.count" => 1, "key.continue" => false}`. TODO: Probably it is subject to change. # # @overload post_process(&block) # Sets post-processor for whole response. Note, that in this case _return_ value of block # is ignored, it is expected that your block will receive response and modify it inplace, # like this: # # ```ruby # post_process do |response| # response['coord'] = Geo::Coord.new(response['lat'], response['lng']) # end # ``` # If you need to replace entire response with something else, see {#post_process_replace} # # @overload post_process(key, &block) # Sets post-processor for one response key. Post-processor is called only if key exists in # the response, and value by this key is replaced with post-processor's response. # # Note, that if `block` returns `nil`, key will be removed completely. # # Usage: # # ```ruby # post_process('date') { |val| Date.parse(val) } # # or, btw, just # post_process('date', &Date.method(:parse)) # ``` # # @param key [String] # @!method post_process_items(key, &block) # Sets post-processors for each items of array, being at `key` (if the key is present in # response, and if its value is array of hashes). # # Inside `block` you can use {#post_process} method as described above (but all of its actions # will be related only to current item of array). # # Example: # # Considering API response like: # # ```json # { # "meta": {"count": 100}, # "data": [ # {"timestamp": "2016-05-01", "value": "10", "dummy": "foo"}, # {"timestamp": "2016-05-02", "value": "13", "dummy": "bar"} # ] # } # ``` # ...you can define postprocessing like this: # # ```ruby # post_process_items 'data' do # post_process 'timestamp', &Date.method(:parse) # post_process 'value', &:to_i # post_process('dummy'){nil} # will be removed # end # ``` # # See also {#post_process} for some generic explanation of post-processing. # # @param key [String] # @!method post_process_replace(&block) # Just like {#post_process} for entire response, but _replaces_ it with what block returns. # # Real-life usage: WorldBank API typically returns responses this way: # # ```json # [ # {"count": 100, "page": 1}, # {"some_data_variable": [{}, {}, {}]} # ] # ``` # ...e.g. metadata and real response as two items in array, not two keys in hash. We can # easily fix this: # # ```ruby # post_process_replace do |response| # {meta: response.first, data: response.last} # end # ``` # # See also {#post_process} for some generic explanation of post-processing. # @!method shared_def(name, &block) # Define reusable parts of definition, which can be utilized with {#use_def}. Common example # is pagination (for one API, pagination logic for all paginated endpoints is typically the # same): # # ```ruby # # at "whole API definition" level: # shared_def :pagination do # param :page, Integer, field: :pg, desc: "Page number, starts from 0" # param :per_page, enum: (5..50), field: :per, desc: "Number of items per page" # end # # # at each particulare endpoint definition, just # use_def :pagination # # ...instead of repeating the param description above. # ``` # # Shared definition block may contain any DSL elements. # # **Works for:** API, namespace, endpoint # @!method use_def(name) # Use shared definition defined earlier. See {#shared_def} for explanation and examples. # # **Works for:** API, namespace, endpoint # @private # If there is no content in class, YARD got mad with directives. # See: https://github.com/lsegal/yard/issues/1207 DUMMY = nil end end require_relative 'dsl/api_builder' require_relative 'dsl/base_builder' require_relative 'dsl/endpoint_builder' require_relative 'dsl/namespace_builder'
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/api_path.rb
lib/tlaw/api_path.rb
# frozen_string_literal: true require 'forwardable' module TLAW # Base class for all API pathes: entire API, namespaces and endpoints. # Allows to define params and post-processors on any level. # class APIPath class << self # @private attr_reader :symbol, :parent, :path, :param_defs, :description, :docs_link # @private attr_writer :parent # @private def define(**args) Class.new(self).tap do |subclass| subclass.setup(**args) end end # @private def definition { symbol: symbol, path: path, description: description, docs_link: docs_link, params: param_defs&.map { |p| [p.name, p.to_h] }.to_h || {} } end # @private def is_defined? # rubocop:disable Naming/PredicateName !symbol.nil? end # @private def full_param_defs [*parent&.full_param_defs, *param_defs] end # @private def required_param_defs param_defs.select(&:required?) end # @private def url_template parent&.url_template or fail "Orphan path #{path}, can't determine full URL" [parent.url_template, path].join end # @return [Array<Class>] def parents Util.parents(self) end protected def setup(symbol:, path:, param_defs: [], description: nil, docs_link: nil) self.symbol = symbol self.path = path self.param_defs = param_defs self.description = description self.param_defs = param_defs self.docs_link = docs_link end attr_writer :symbol, :param_defs, :path, :description, :xml, :docs_link end extend Forwardable # @private attr_reader :parent, :params def initialize(parent, **params) @parent = parent @params = params end # @return [Array<APIPath>] def parents Util.parents(self) end def_delegators :self_class, :describe # @private # Could've been protected, but it hurts testability :shrug: def prepared_params (parent&.prepared_params || {}).merge(prepare_params(@params)) end protected def api is_a?(API) ? self : parent&.api end private def_delegators :self_class, :param_defs, :required_param_defs def prepare_params(arguments) guard_missing!(arguments) guard_unknown!(arguments) param_defs .map { |dfn| [dfn, arguments[dfn.name]] } .reject { |_, v| v.nil? } .map { |dfn, arg| dfn.(arg) } .inject(&:merge) &.transform_keys(&:to_sym) || {} end def guard_unknown!(arguments) arguments.keys.-(param_defs.map(&:name)).yield_self { |unknown| unknown.empty? or fail ArgumentError, "Unknown arguments: #{unknown.join(', ')}" } end def guard_missing!(arguments) required_param_defs.map(&:name).-(arguments.keys).yield_self { |missing| missing.empty? or fail ArgumentError, "Missing arguments: #{missing.join(', ')}" } end # For def_delegators def self_class self.class end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/data_table.rb
lib/tlaw/data_table.rb
# frozen_string_literal: true module TLAW # Basically, just a 2-d array with column names. Or you can think of # it as an array of hashes. Or loose DataFrame implementation. # # Just like this: # # ```ruby # tbl = DataTable.new([ # {id: 1, name: 'Mike', salary: 1000}, # {id: 2, name: 'Doris', salary: 900}, # {id: 3, name: 'Angie', salary: 1200} # ]) # # => #<TLAW::DataTable[id, name, salary] x 3> # tbl.count # # => 3 # tbl.keys # # => ["id", "name", "salary"] # tbl[0] # # => {"id"=>1, "name"=>"Mike", "salary"=>1000} # tbl['salary'] # # => [1000, 900, 1200] # ``` # # Basically, that's it. Every array of hashes in TLAW response will be # converted into corresponding `DataTable`. # class DataTable < Array def self.from_columns(column_names, columns) from_rows(column_names, columns.transpose) end def self.from_rows(column_names, rows) new(rows.map { |r| column_names.zip(r).to_h }) end # Creates DataTable from array of hashes. # # Note, that all hash keys are stringified, and all hashes are expanded # to have same set of keys. # # @param hashes [Array<Hash>] def initialize(hashes) hashes = hashes.each_with_index(&method(:enforce_hash!)) .map { |h| h.transform_keys(&:to_s) } empty = hashes.map(&:keys).flatten.uniq.map { |k| [k, nil] }.to_h hashes = hashes.map(&empty.method(:merge)) super(hashes) end # All column names. # # @return [Array<String>] def keys empty? ? [] : first.keys end # Allows access to one column or row. # # @overload [](index) # Returns one row from a DataTable. # # @param index [Integer] Row number # @return [Hash] Row as a hash # # @overload [](column_name) # Returns one column from a DataTable. # # @param column_name [String] Name of column # @return [Array] Column as an array of all values in it # def [](index_or_column) case index_or_column when Integer super when String, Symbol map { |h| h[index_or_column.to_s] } else fail ArgumentError, 'Expected integer or string/symbol index' \ ", got #{index_or_column.class}" end end # Slice of a DataTable with only specified columns left. # # @param names [Array<String>] What columns to leave in a DataTable # @return [DataTable] def columns(*names) names.map!(&:to_s) DataTable.new(map { |h| names.map { |n| [n, h[n]] }.to_h }) end # Represents DataTable as a `column name => all values in columns` # hash. # # @return [Hash{String => Array}] def to_h keys.map { |k| [k, map { |h| h[k] }] }.to_h end # @private def inspect "#<#{self.class.name}[#{keys.join(', ')}] x #{size}>" end # @private def pretty_print(printer) printer.text("#<#{self.class.name}[#{keys.join(', ')}] x #{size}>") end private def enforce_hash!(val, idx) val.is_a?(Hash) or fail ArgumentError, "All rows are expected to be hashes, row #{idx} is #{val.class}" end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/endpoint.rb
lib/tlaw/endpoint.rb
# frozen_string_literal: true require 'faraday' require 'faraday_middleware' require 'addressable/template' require 'crack' module TLAW # Represents API endpoint. # # You will neither create nor use endpoint descendants or instances directly: # # * endpoint class definition is performed through {DSL} helpers, # * and then, containing namespace obtains `.<endpoint_name>()` method, which is (almost) # everything you need to know. # class Endpoint < APIPath class << self # @private attr_reader :processors # Inspects endpoint class prettily. # # Example: # # ```ruby # some_api.some_namespace.endpoint(:my_endpoint) # # => <SomeApi::SomeNamespace::MyEndpoint call-sequence: my_endpoint(param1, param2: nil), docs: .describe> # ``` # # @return [String] def inspect return super unless is_defined? Formatting::Inspect.endpoint_class(self) end # @return [Formatting::Description] def describe return '' unless is_defined? Formatting::Describe.endpoint_class(self) end protected def setup(processors: [], **args) super(**args) self.processors = processors.dup end attr_writer :processors end # @private attr_reader :url, :request_params # Creates endpoint class (or descendant) instance. Typically, you never use it directly. # # Params defined in parent namespace are passed here. # def initialize(parent, **params) super template = Addressable::Template.new(url_template) # .normalize fixes ../ in path @url = template.expand(**prepared_params).normalize.to_s.yield_self(&method(:fix_slash)) url_keys = template.keys.map(&:to_sym) @request_params = prepared_params.reject { |k,| url_keys.include?(k) } end # Does the real call to the API, with all params passed to this method and to parent namespace. # # Typically, you don't use it directly, that's what called when you do # `some_namespace.endpoint_name(**params)`. # # @return [Hash,Array] Parsed, flattened and post-processed response body. def call # TODO: we have a whole response here, so we can potentially have processors that # extract some useful information (pagination, rate-limiting) from _headers_. api.request(url, **request_params).body.yield_self(&method(:parse)) end # @return [String] def inspect Formatting::Inspect.endpoint(self) end # @private def to_curl separator = url.include?('?') ? '&' : '?' full_url = url + separator + request_params.map(&'%s=%s'.method(:%)).join('&') # FIXME: Probably unreliable (escaping), but Shellwords.escape do the wrong thing. %{curl "#{full_url}"} end private def_delegators :self_class, :url_template, :processors # Fix params substitution: if it was in path part, we shouldn't have escaped "/" # E.g. for template `http://google.com/{foo}/bar`, and foo="some/path", Addressable would # produce "http://google.com/some%2fpath/bar", but we want "http://google.com/some/path/bar" def fix_slash(url) url, query = url.split('?', 2) url.gsub!('%2F', '/') [url, query].compact.join('?') end def parse(body) processors.inject(body) { |res, proc| proc.(res) } end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/util.rb
lib/tlaw/util.rb
# frozen_string_literal: true module TLAW # @private module Util module_function def camelize(string) string.sub(/^[a-z\d]*/, &:capitalize) end def deindent(string) string .gsub(/^[ \t]+/, '') # first, remove spaces at a beginning of each line .gsub(/\A\n|\n\s*\Z/, '') # then, remove empty lines before and after docs block end # Returns [parent, parent.parent, ...] def parents(obj) result = [] cursor = obj while (cursor = cursor.parent) result << cursor end result end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/dsl/namespace_builder.rb
lib/tlaw/dsl/namespace_builder.rb
# frozen_string_literal: true require_relative 'base_builder' require_relative 'endpoint_builder' module TLAW module DSL # @private class NamespaceBuilder < BaseBuilder CHILD_CLASSES = {NamespaceBuilder => Namespace, EndpointBuilder => Endpoint}.freeze attr_reader :children ENDPOINT_METHOD = <<~CODE def %{call_sequence} child(:%{symbol}, Endpoint, %{params}).call end CODE NAMESPACE_METHOD = <<~CODE def %{call_sequence} child(:%{symbol}, Namespace, %{params}) end CODE METHODS = {Endpoint => ENDPOINT_METHOD, Namespace => NAMESPACE_METHOD}.freeze def initialize(children: [], **args, &block) @children = children.map { |c| [c.symbol, c] }.to_h super(**args, &block) end def definition super.merge(children: children.values) end def endpoint(symbol, path = nil, **opts, &block) child(EndpointBuilder, symbol, path, **opts, &block) end def namespace(symbol, path = nil, **opts, &block) child(NamespaceBuilder, symbol, path, **opts, &block) end def finalize Namespace.define(**definition).tap(&method(:define_children_methods)) end private def child(builder_class, symbol, path, **opts, &block) symbol = symbol.to_sym target_class = CHILD_CLASSES.fetch(builder_class) existing = children[symbol] &.tap { |c| c < target_class or fail ArgumentError, "#{symbol} already defined as #{c.ansestors.first}" } &.definition || {} builder_class.new( symbol: symbol, path: path, context: self, **opts, **existing, &block ).finalize.tap { |child| children[symbol] = child } end def define_children_methods(namespace) children.each_value do |child| namespace.module_eval(child_method_code(child)) end end def child_method_code(child) params = child.param_defs.map { |par| "#{par.name}: #{par.name}" }.join(', ') METHODS.fetch(child.ancestors[1]) % { call_sequence: Formatting.call_sequence(child), symbol: child.symbol, params: params } end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/dsl/api_builder.rb
lib/tlaw/dsl/api_builder.rb
# frozen_string_literal: true require_relative 'base_builder' require_relative 'endpoint_builder' require_relative 'namespace_builder' module TLAW module DSL # @private class ApiBuilder < NamespaceBuilder # @private CLASS_NAMES = { :[] => 'Element' }.freeze def initialize(api_class, &block) @api_class = api_class @definition = {} # super(symbol: nil, children: api_class.children || [], &block) super(symbol: nil, **api_class.definition, &block) end def finalize @api_class.setup(**definition) define_children_methods(@api_class) constantize_children(@api_class) end def base(url) @definition[:base_url] = url end private def constantize_children(namespace) return unless namespace.name&.match?(/^[A-Z]/) && namespace.respond_to?(:children) namespace.children.each do |child| class_name = CLASS_NAMES.fetch(child.symbol, Util.camelize(child.symbol.to_s)) # namespace.send(:remove_const, class_name) if namespace.const_defined?(class_name) namespace.const_set(class_name, child) unless namespace.const_defined?(class_name) constantize_children(child) end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/dsl/endpoint_builder.rb
lib/tlaw/dsl/endpoint_builder.rb
# frozen_string_literal: true require_relative 'base_builder' module TLAW module DSL # @private class EndpointBuilder < BaseBuilder def definition # TODO: Here we'll be more flexible in future, allowing to avoid flatten/datablize all_processors = [ @parser, ResponseProcessors.method(:flatten), *processors, ResponseProcessors.method(:datablize) ] super.merge(processors: all_processors) end def finalize Endpoint.define(**definition) end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/dsl/base_builder.rb
lib/tlaw/dsl/base_builder.rb
# frozen_string_literal: true module TLAW module DSL # @private class BaseBuilder attr_reader :params, :processors, :shared_definitions def initialize(symbol:, path: nil, context: nil, xml: false, params: {}, **opts, &block) path ||= "/#{symbol}" # Not default arg, because we need to process explicitly passed path: nil, too @definition = opts.merge(symbol: symbol, path: path) @params = params.merge(params_from_path(path)) @processors = (context&.processors || []).dup @parser = parser(xml) @shared_definitions = context&.shared_definitions || {} instance_eval(&block) if block end def definition @definition.merge(param_defs: params.map { |name, **opts| Param.new(name: name, **opts) }) end def docs(link) @definition[:docs_link] = link self end def description(text) @definition[:description] = Util.deindent(text) self end alias desc description def param(name, type = nil, enum: nil, desc: nil, description: desc, **opts) opts = opts.merge( type: type || enum&.yield_self(&method(:enum_type)), description: description&.yield_self(&Util.method(:deindent)) ).compact params.merge!(name => opts) { |_, o, n| o.merge(n) } self end def shared_def(name, &block) @shared_definitions[name] = block self end def use_def(name) shared_definitions .fetch(name) { fail ArgumentError, "#{name.inspect} is not a shared definition" } .tap { |block| instance_eval(&block) } self end def finalize fail NotImplementedError, "#{self.class} doesn't implement #finalize" end G = ResponseProcessors::Generators def post_process(key_pattern = nil, &block) @processors << (key_pattern ? G.transform_by_key(key_pattern, &block) : G.mutate(&block)) end # @private class PostProcessProxy def initialize(owner, parent_key) @owner = owner @parent_key = parent_key end def post_process(key = nil, &block) @owner.processors << G.transform_nested(@parent_key, key, &block) end end def post_process_items(key_pattern, &block) PostProcessProxy.new(self, key_pattern).instance_eval(&block) end def post_process_replace(&block) @processors << block end private def parser(xml) xml ? Crack::XML.method(:parse) : JSON.method(:parse) end def enum_type(enum) case enum when Hash enum when Enumerable # well... in fact respond_to?(:each) probably will do enum.map { |v| [v, v] }.to_h else fail ArgumentError, "Can't construct enum from #{enum.inspect}" end end def params_from_path(path) Addressable::Template.new(path).keys.map { |key| [key.to_sym, keyword: false] }.to_h end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/formatting/inspect.rb
lib/tlaw/formatting/inspect.rb
# frozen_string_literal: true module TLAW module Formatting # @private module Inspect class << self def endpoint(object) _object(object) end def namespace(object) _object(object, children_list(object.class)) end def endpoint_class(klass) _class(klass, 'endpoint') end def namespace_class(klass) _class(klass, 'namespace', children_list(klass)) end private def children_list(namespace) ns = " namespaces: #{namespace.namespaces.map(&:symbol).join(', ')};" \ unless namespace.namespaces.empty? ep = " endpoints: #{namespace.endpoints.map(&:symbol).join(', ')};" \ unless namespace.endpoints.empty? [ns, ep].compact.join end def _object(object, addition = '') "#<#{object.class.name}(" + object.params.map { |name, val| "#{name}: #{val.inspect}" }.join(', ') + ');' + addition + ' docs: .describe>' end def _class(klass, type, addition = '') (klass.name || "(unnamed #{type} class)") + "(call-sequence: #{Formatting.call_sequence(klass)};" + addition + ' docs: .describe)' end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/formatting/describe.rb
lib/tlaw/formatting/describe.rb
# frozen_string_literal: true module TLAW module Formatting # @private module Describe class << self def endpoint_class(klass) [ Formatting.call_sequence(klass), klass.description&.yield_self { |desc| "\n" + indent(desc, ' ') }, klass.docs_link&.yield_self(&"\n Docs: %s".method(:%)), param_defs(klass.param_defs) ].compact.join("\n").yield_self(&Description.method(:new)) end def namespace_class(klass) [ endpoint_class(klass), nested(klass.namespaces, 'Namespaces'), nested(klass.endpoints, 'Endpoints') ].join.yield_self(&Description.method(:new)) end private def short(klass) descr = klass.description&.yield_self { |d| "\n" + indent(first_para(d), ' ') } ".#{Formatting.call_sequence(klass)}#{descr}" end def nested(klasses, title) return '' if klasses.empty? "\n\n #{title}:\n\n" + klasses.map(&method(:short)) .map { |cd| indent(cd, ' ') } .join("\n\n") end def param_defs(defs) return nil if defs.empty? defs .map(&method(:param_def)) .join("\n") .yield_self { |s| "\n" + indent(s, ' ') } end def param_def(param) [ '@param', param.name, doc_type(param.type)&.yield_self { |t| "[#{t}]" }, param.description, possible_values(param.type), param.default&.yield_self { |d| "(default = #{d.inspect})" } ].compact.join(' ').gsub(/ +\n/, "\n") end def possible_values(type) return unless type.respond_to?(:possible_values) "\n Possible values: #{type.possible_values}" end def doc_type(type) case type when Param::ClassType type.type.name when Param::DuckType "##{type.type}" end end def first_para(str) str.split("\n\n").first end def indent(str, indentation = ' ') str.gsub(/(\A|\n)/, '\1' + indentation) end end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
molybdenum-99/tlaw
https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/param/type.rb
lib/tlaw/param/type.rb
# frozen_string_literal: true module TLAW class Param # @private class Type attr_reader :type def self.default_type @default_type ||= Type.new(nil) end def self.coerce(type = nil) case type when nil default_type when Type type when Class ClassType.new(type) when Symbol DuckType.new(type) when Hash EnumType.new(type) else fail ArgumentError, "Undefined type #{type}" end end def initialize(type) @type = type end def ==(other) other.is_a?(self.class) && other.type == type end def call(value) validation_error(value) &.yield_self { |msg| fail TypeError, "expected #{msg}, got #{value.inspect}" } _convert(value) end private def validation_error(_value) nil end def _convert(value) value end end # @private class ClassType < Type private def validation_error(value) "instance of #{type}" unless value.is_a?(type) end def _convert(value) value end end # @private class DuckType < Type private def _convert(value) value.send(type) end def validation_error(value) "object responding to ##{type}" unless value.respond_to?(type) end end # @private class EnumType < Type def possible_values type.keys.map(&:inspect).join(', ') end private def validation_error(value) "one of #{possible_values}" unless type.key?(value) end def _convert(value) type.fetch(value) end end end end
ruby
MIT
922ecb7994b91aafda56582d7a69e230d14a19db
2026-01-04T17:55:02.922765Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/app/app_delegate.rb
app/app_delegate.rb
class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) true end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/operation_spec.rb
spec/operation_spec.rb
describe Elevate::ElevateOperation do before do @target = lambda { 42 } @operation = Elevate::ElevateOperation.alloc.initWithTarget(@target, args: {}, channel: []) @queue = NSOperationQueue.alloc.init end after do @queue.waitUntilAllOperationsAreFinished end describe "#exception" do describe "when no exception is raised" do it "returns nil" do @queue.addOperation(@operation) @operation.waitUntilFinished @operation.exception.should.be.nil end end describe "when an exception is raised" do it "returns the exception" do @target = lambda { raise IndexError } @operation = Elevate::ElevateOperation.alloc.initWithTarget(@target, args: {}, channel: nil) @queue.addOperation(@operation) @operation.waitUntilFinished @operation.exception.should.not.be.nil end end end describe "#result" do before do @target = lambda { 42 } @operation = Elevate::ElevateOperation.alloc.initWithTarget(@target, args: {}, channel: nil) end describe "before starting the operation" do it "returns nil" do @operation.result.should.be.nil end end describe "when the operation has been cancelled" do it "returns nil" do @operation.cancel @queue.addOperation(@operation) @operation.waitUntilFinished @operation.result.should.be.nil end end describe "when the operation has finished" do it "returns the result of the lambda" do @queue.addOperation(@operation) @operation.waitUntilFinished @operation.result.should == 42 end end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/io_coordinator_spec.rb
spec/io_coordinator_spec.rb
describe Elevate::IOCoordinator do before do @coordinator = Elevate::IOCoordinator.new end it "is not cancelled" do @coordinator.should.not.be.cancelled end describe "#install" do it "stores the coordinator in a thread-local variable" do @coordinator.install() Thread.current[:io_coordinator].should == @coordinator end end [:signal_blocked, :signal_unblocked].each do |method| describe method.to_s do describe "when IO has not been cancelled" do it "does not raise CancelledError" do lambda { @coordinator.send(method, 42) }.should.not.raise end end describe "when IO was cancelled" do it "raises CancelledError" do @coordinator.cancel() lambda { @coordinator.send(method, "hello") }.should.raise(Elevate::CancelledError) end end describe "when IO has timed out" do it "raises TimeoutError" do @coordinator.cancel(Elevate::TimeoutError) lambda { @coordinator.send(method, "hello") }.should.raise(Elevate::TimeoutError) end end end end describe "#uninstall" do it "removes the coordinator from a thread-local variable" do @coordinator.install() @coordinator.uninstall() Thread.current[:io_coordinator].should.be.nil end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/elevate_spec.rb
spec/elevate_spec.rb
class TestController include Elevate def initialize @invocations = {} @counter = 0 @threads = [] @updates = [] @callback_args = nil @completion = nil end attr_accessor :started attr_accessor :result attr_accessor :exception attr_accessor :invocations attr_accessor :counter attr_accessor :threads attr_accessor :updates attr_accessor :callback_args attr_accessor :completion task :cancellable do background do task_args[:semaphore].wait update 42 nil end on_start do self.invocations[:start] = counter self.counter += 1 end on_finish do |result, ex| self.invocations[:finish] = counter self.counter += 1 end on_update do |n| self.invocations[:update] = counter self.counter += 1 end end task :custom_error_handlers do background do raise TimeoutError end on_error do |e| self.invocations[:error] = counter self.counter += 1 end on_timeout do |e| self.invocations[:timeout] = counter self.counter += 1 end end task :test_task do background do sleep 0.05 update 1 raise Elevate::TimeoutError if task_args[:raise] sleep 0.1 update 2 42 end on_start do self.invocations[:start] = counter self.callback_args = task_args self.counter += 1 self.threads << NSThread.currentThread end on_update do |num| self.updates << num self.invocations[:update] = counter self.counter += 1 self.threads << NSThread.currentThread end on_error do |e| self.invocations[:error] = counter self.counter += 1 end on_finish do |result, exception| self.invocations[:finish] = counter self.counter += 1 self.threads << NSThread.currentThread self.result = result self.exception = exception #Dispatch::Queue.main.async { resume } end end task :timeout_test do timeout 0.3 background do Elevate::HTTP.get("http://example.com/") end on_timeout do |e| self.invocations[:timeout] = counter self.counter += 1 end on_finish do |result, ex| self.invocations[:finish] = counter self.counter += 1 @completion.call if @completion end end end describe Elevate do extend WebStub::SpecHelpers before do @controller = TestController.new end describe "#cancel" do describe "when no tasks are running" do it "does nothing" do ->{ @controller.cancel(:test_task) }.should.not.raise end end describe "when a single task is running" do it "cancels the task and does not invoke callbacks" do semaphore = Dispatch::Semaphore.new(0) @controller.launch(:cancellable, semaphore: semaphore) @controller.cancel(:cancellable) semaphore.signal wait 0.5 do @controller.invocations[:update].should.be.nil @controller.invocations[:finish].should.be.nil end end end describe "when several tasks are running" do it "cancels all of them" do semaphore = Dispatch::Semaphore.new(0) @controller.launch(:cancellable, semaphore: semaphore) @controller.launch(:cancellable, semaphore: semaphore) @controller.launch(:cancellable, semaphore: semaphore) @controller.cancel(:cancellable) semaphore.signal wait 0.5 do @controller.invocations[:update].should.be.nil @controller.invocations[:finish].should.be.nil end end end end describe "#launch" do it "runs the task asynchronously, returning the result" do @controller.launch(:test_task, raise: false) wait 0.5 do @controller.result.should == 42 end end it "allows tasks to report progress" do @controller.launch(:test_task, raise: false) wait 0.5 do @controller.updates.should == [1, 2] end end it "invokes all callbacks on the UI thread" do @controller.launch(:test_task, raise: false) wait 0.5 do @controller.threads.each { |t| t.isMainThread.should.be.true } end end it "sets task_args to args used at launch" do @controller.launch(:test_task, raise: true) wait 0.5 do @controller.callback_args.should == { raise: true } end end it "invokes on_error when an exception occurs" do @controller.launch(:test_task, raise: true) wait 0.5 do @controller.invocations[:error].should.not.be.nil end end it "invokes on_start before on_finish" do @controller.launch(:test_task, raise: false) wait 0.5 do @controller.invocations[:start].should < @controller.invocations[:finish] end end it "invokes on_update before on_finish" do @controller.launch(:test_task, raise: false) wait 0.5 do invocations = @controller.invocations invocations[:update].should < invocations[:finish] end end it "invokes on_update after on_start" do @controller.launch(:test_task, raise: false) wait 0.5 do invocations = @controller.invocations invocations[:update].should > invocations[:start] end end end describe "error handling" do it "invokes an error handling correspding to the raised exception" do @controller.launch(:custom_error_handlers) wait 0.5 do invocations = @controller.invocations invocations[:timeout].should.not.be.nil invocations[:error].should.be.nil end end it "invokes on_error if there is not a specific handler" do @controller.launch(:test_task, raise: true) wait 0.5 do invocations = @controller.invocations invocations[:error].should.not.be.nil end end end describe "timeouts" do it "does not cancel the operation if it completes in time" do stub_request(:get, "http://example.com/"). to_return(body: "Hello!", content_type: "text/plain") @controller.completion = -> { resume } @controller.launch(:timeout_test) wait_max 0.9 do @controller.invocations[:timeout].should.be.nil @controller.invocations[:finish].should.not.be.nil end end it "stops the operation when it exceeds the timeout" do stub_request(:get, "http://example.com/"). to_return(body: "Hello!", content_type: "text/plain", delay: 1.0) @controller.completion = -> { resume } @controller.launch(:timeout_test) wait_max 0.9 do @controller.invocations[:finish].should.not.be.nil end end it "invokes on_timeout when the operation times out" do stub_request(:get, "http://example.com/"). to_return(body: "Hello!", content_type: "text/plain", delay: 1.0) @controller.completion = -> { resume } @controller.launch(:timeout_test) wait_max 0.9 do @controller.invocations[:timeout].should.not.be.nil end end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/task_context_spec.rb
spec/task_context_spec.rb
describe Elevate::TaskContext do describe "#execute" do it "runs the specified block" do result = {} context = Elevate::TaskContext.new(->{ result[:ret] = true }, [], {}) context.execute result[:ret].should.be.true end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/http_spec.rb
spec/http_spec.rb
describe Elevate::HTTP do extend WebStub::SpecHelpers before { disable_network_access! } after { enable_network_access! } before do @url = "http://www.example.com/" end Elevate::HTTP::Request::METHODS.each do |m| describe ".#{m}" do it "synchronously issues a HTTP #{m} request" do stub = stub_request(m, @url) Elevate::HTTP.send(m, @url) stub.should.be.requested end end end describe "Request options" do it "encodes query string of :headers" do stub = stub_request(:get, "#{@url}?a=1&b=hello&c=4.2") Elevate::HTTP.get(@url, query: { a: 1, b: "hello", c: "4.2" }) stub.should.be.requested end it "sends headers specified by :headers" do stub = stub_request(:get, @url). with(headers: { "API-Key" => "secret" }) Elevate::HTTP.get(@url, headers: { "API-Key" => "secret" }) stub.should.be.requested end it "sends body content specified by :body" do stub = stub_request(:post, @url).with(body: "hello") Elevate::HTTP.post(@url, body: "hello".dataUsingEncoding(NSUTF8StringEncoding)) stub.should.be.requested end describe "with a JSON body" do it "encodes JSON dictionary specified by :json" do stub = stub_request(:post, @url).with(body: '{"test":"secret"}') Elevate::HTTP.post(@url, json: { "test" => "secret" }) stub.should.be.requested end it "encodes JSON array specified by :json" do stub = stub_request(:post, @url).with(body: '["1","2"]') Elevate::HTTP.post(@url, json: ["1", "2"]) stub.should.be.requested end it "sets the correct Content-Type" do stub = stub_request(:post, @url). with(body: '{"test":"secret"}', headers: { "Content-Type" => "application/json" }) Elevate::HTTP.post(@url, json: { "test" => "secret" }) stub.should.be.requested end end describe "with a form body" do it "encodes form data specified by :form" do stub = stub_request(:post, @url).with(body: { "test" => "secret", "user" => "matt" }) Elevate::HTTP.post(@url, form: { "test" => "secret", "user" => "matt" }) stub.should.be.requested end it "sets the correct Content-Type" do stub = stub_request(:post, @url). with(body: { "test" => "secret", "user" => "matt" }, headers: { "Content-Type" => "application/x-www-form-urlencoded" }) Elevate::HTTP.post(@url, form: { "test" => "secret", "user" => "matt" }) stub.should.be.requested end end end describe "Response" do it "returns a Response" do stub_request(:get, @url). to_return(body: "hello", headers: { "X-TestHeader" => "Value" }, status_code: 204) response = Elevate::HTTP.get(@url) NSString.alloc.initWithData(response.body, encoding: NSUTF8StringEncoding).should == "hello" NSString.alloc.initWithData(response.raw_body, encoding: NSUTF8StringEncoding).should == "hello" response.error.should.be.nil response.headers.keys.should.include("X-TestHeader") response.status_code.should == 204 response.url.should == @url end describe "when the response is encoded as JSON" do it "should automatically decode it" do stub_request(:get, @url). to_return(json: { user_id: "3", token: "secret" }) response = Elevate::HTTP.get(@url) response.body.should == { "user_id" => "3", "token" => "secret" } end describe "when a JSON dictionary is returned" do it "the returned response should behave like a Hash" do stub_request(:get, @url). to_return(json: { user_id: "3", token: "secret" }) response = Elevate::HTTP.get(@url) response["user_id"].should == "3" end end describe "when a JSON array is returned" do it "the returned response should behave like an Array" do stub_request(:get, @url). to_return(json: ["apple", "orange", "pear"]) response = Elevate::HTTP.get(@url) response.length.should == 3 end end end describe "when the response is redirected" do it "redirects to the final URL" do @redirect_url = @url + "redirected" stub_request(:get, @redirect_url).to_return(body: "redirected") stub_request(:get, @url).to_redirect(url: @redirect_url) response = Elevate::HTTP.get(@url) response.url.should == @redirect_url end describe "with an infinite redirect loop" do before do @url2 = @url + "redirect" stub_request(:get, @url).to_redirect(url: @url2) stub_request(:get, @url2).to_redirect(url: @url) end it "raises a RequestError" do lambda { Elevate::HTTP.get(@url) }. should.raise(Elevate::HTTP::RequestError) end end end #describe "when the response has a HTTP error status" do #it "raises RequestError" do #stub_request(m, @url).to_return(status_code: 422) #lambda { Elevate::HTTP.send(m, @url) }.should.raise(Elevate::HTTP::RequestError) #end #end describe "when the request cannot be fulfilled" do it "raises a RequestError" do lambda { Elevate::HTTP.get(@url) }. should.raise(Elevate::HTTP::RequestError) end end describe "when the Internet connection is offline" do it "raises an OfflineError" do stub_request(:get, @url).to_fail(code: NSURLErrorNotConnectedToInternet) lambda { Elevate::HTTP.get(@url) }. should.raise(Elevate::HTTP::OfflineError) end end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/http/request_spec.rb
spec/http/request_spec.rb
describe Elevate::HTTP::Request do extend WebStub::SpecHelpers before do disable_network_access! end before do @url = "http://www.example.com/" @body = "hello" end it "requires a valid HTTP method" do lambda { Elevate::HTTP::Request.new(:invalid, @url) }.should.raise(ArgumentError) end it "requires a URL starting with http" do lambda { Elevate::HTTP::Request.new(:get, "asdf") }.should.raise(ArgumentError) end it "requires the body to be an instance of NSData" do lambda { Elevate::HTTP::Request.new(:get, @url, body: @body) }.should.raise(ArgumentError) end describe "fulfilling a GET request" do before do stub_request(:get, @url). to_return(body: @body, headers: {"Content-Type" => "text/plain"}, status_code: 201) @request = Elevate::HTTP::Request.new(:get, @url) @response = @request.response end it "response has the correct status code" do @response.status_code.should == 201 end it "response has the right body" do NSString.alloc.initWithData(@response.body, encoding:NSUTF8StringEncoding).should == @body end it "response has the correct headers" do @response.headers.should == { "Content-Type" => "text/plain" } end it "response has no errors" do @response.error.should.be.nil end end describe "fulfilling a GET request with headers" do before do stub_request(:get, @url).with(headers: { "API-Token" => "abc123" }).to_return(body: @body) @request = Elevate::HTTP::Request.new(:get, @url, headers: { "API-Token" => "abc123" }) @response = @request.response end it "includes the headers in the request" do @response.body.should.not.be.nil end end describe "fulfilling a POST request with a body" do before do stub_request(:post, @url).with(body: @body).to_return(body: @body) end it "sends the body as part of the request" do request = Elevate::HTTP::Request.new(:post, @url, body: @body.dataUsingEncoding(NSUTF8StringEncoding)) response = request.response NSString.alloc.initWithData(response.body, encoding:NSUTF8StringEncoding).should == @body end end describe "cancelling a request" do before do stub_request(:get, @url).to_return(body: @body, delay: 1.0) end it "aborts the request" do start = Time.now request = Elevate::HTTP::Request.new(:get, @url) request.send request.cancel response = request.response # simulate blocking finish = Time.now (finish - start).should < 1.0 end it "sets the response to nil" do request = Elevate::HTTP::Request.new(:get, @url) request.send request.cancel request.response.should.be.nil end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/http/http_client_spec.rb
spec/http/http_client_spec.rb
describe Elevate::HTTP::HTTPClient do extend WebStub::SpecHelpers before do disable_network_access! @base_url = "http://www.example.com" @path = "/resource/action" @url = @base_url + @path @client = Elevate::HTTP::HTTPClient.new(@base_url) end it "issues requests to the complete URL" do stub_request(:get, @url).to_return(status_code: 201) @client.get(@path).status_code.should == 201 end it "appends query parameters to the URL" do stub_request(:get, @url + "?q=help&page=2").to_return(json: { result: 0 }) @client.get(@path, q: "help", page: 2).body.should == { "result" => 0 } end it "decodes JSON responses" do result = { "int" => 42, "string" => "hi", "dict" => { "boolean" => true }, "array" => [1,2,3] } stub_request(:get, @url).to_return(json: result) @client.get(@path).body.should == result end it "encodes JSON bodies" do stub_request(:post, @url). with(json: { string: "hello", array: [1,2,3] }). to_return(json: { result: true }) @client.post(@path, { string: "hello", array: [1,2,3] }).body.should == { "result" => true } end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/spec/http/activity_indicator_spec.rb
spec/http/activity_indicator_spec.rb
describe Elevate::HTTP::ActivityIndicator do before do UIApplication.sharedApplication.setNetworkActivityIndicatorVisible(false) @indicator = Elevate::HTTP::ActivityIndicator.new end describe ".instance" do it "returns a singleton instance" do instance = Elevate::HTTP::ActivityIndicator.instance instance2 = Elevate::HTTP::ActivityIndicator.instance instance.object_id.should == instance2.object_id end end describe "#hide" do it "does nothing if it isn't shown" do @indicator.hide UIApplication.sharedApplication.isNetworkActivityIndicatorVisible.should.be.false end it "hides the indicator only if there are no outstanding show requests" do @indicator.show @indicator.show @indicator.hide UIApplication.sharedApplication.isNetworkActivityIndicatorVisible.should.be.true @indicator.hide UIApplication.sharedApplication.isNetworkActivityIndicatorVisible.should.be.false end end describe "#show" do it "shows the activity indicator" do @indicator.show UIApplication.sharedApplication.isNetworkActivityIndicatorVisible.should.be.true end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate.rb
lib/elevate.rb
require 'elevate/version' unless defined?(Motion::Project::Config) raise "This file must be required within a RubyMotion project Rakefile." end Motion::Project::App.setup do |app| Dir.glob(File.join(File.dirname(__FILE__), "elevate/**/*.rb")).each do |file| app.files.unshift(file) end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate/task.rb
lib/elevate/task.rb
module Elevate class Task def initialize(definition, controller, active_tasks) @definition = definition @controller = WeakRef.new(controller) @active_tasks = active_tasks @operation = nil @channel = Channel.new(method(:on_update)) @args = nil @timer = nil end def cancel if @operation @operation.cancel if @timer @timer.invalidate end end end def name @definition.name end def start(args) @operation = ElevateOperation.alloc.initWithTarget(@definition.handlers[:background], args: args, channel: WeakRef.new(@channel)) @operation.addObserver(self, forKeyPath: "isFinished", options: NSKeyValueObservingOptionNew, context: nil) queue.addOperation(@operation) @active_tasks << self @args = args if interval = @definition.options[:timeout_interval] @timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: :"on_timeout:", userInfo: nil, repeats: false) end performSelectorOnMainThread(:on_start, withObject: nil, waitUntilDone: false) end private def error_handler_for(exception) handler_name = exception.class.name handler_name = handler_name.split("::").last handler_name.gsub!(/Error$/, "") handler_name.gsub!(/(.)([A-Z])/) { |m| "#{$1}_#{$2.downcase}" } handler_name = "on_" + handler_name.downcase handler_name.to_sym end def invoke(handler_name, *args) return false if @operation.isCancelled block = @definition.handlers[handler_name] return false unless block @controller.task_args = @args @controller.instance_exec(*args, &block) @controller.task_args = nil true end def queue Dispatch.once do $elevate_queue = NSOperationQueue.alloc.init $elevate_queue.maxConcurrentOperationCount = 1 end $elevate_queue end def observeValueForKeyPath(path, ofObject: operation, change: change, context: ctx) case path when "isFinished" performSelectorOnMainThread(:on_finish, withObject: nil, waitUntilDone: false) end end def on_start invoke(:on_start) end def on_finish @operation.removeObserver(self, forKeyPath: "isFinished") @active_tasks.delete(self) if @timer @timer.invalidate end if exception = @operation.exception invoke(error_handler_for(exception), exception) || invoke(:on_error, exception) end invoke(:on_finish, @operation.result, @operation.exception) end def on_timeout(timer) @operation.timeout end def on_update(args) unless NSThread.isMainThread performSelectorOnMainThread(:"on_update:", withObject: args, waitUntilDone: false) return end invoke(:on_update, *args) end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate/version.rb
lib/elevate/version.rb
module Elevate VERSION = "0.7.0" end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate/task_definition.rb
lib/elevate/task_definition.rb
module Elevate class TaskDefinition def initialize(name, options, &block) @name = name @options = options @handlers = {} instance_eval(&block) end attr_reader :name attr_reader :handlers attr_reader :options def method_missing(method, *args, &block) if method.to_s.start_with?("on_") raise ArgumentError, "wrong number of arguments" unless args.empty? raise ArgumentError, "block not supplied" unless block_given? @handlers[method.to_sym] = block else super end end def respond_to_missing?(method, include_private = false) method.to_s.start_with?("on_") || super end def background(&block) @handlers[:background] = block end def on_error(&block) raise "on_error blocks must accept one parameter" unless block.arity == 1 @handlers[:on_error] = block end def on_finish(&block) raise "on_finish blocks must accept two parameters" unless block.arity == 2 @handlers[:on_finish] = block end def on_start(&block) raise "on_start blocks must accept zero parameters" unless block.arity == 0 @handlers[:on_start] = block end def on_update(&block) @handlers[:on_update] = block end def timeout(seconds) raise "timeout argument must be a number" unless seconds.is_a?(Numeric) @options[:timeout_interval] = seconds end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate/channel.rb
lib/elevate/channel.rb
module Elevate # A simple unidirectional stream of data with a single consumer. # # @api private class Channel def initialize(block) @target = block end # Pushes data to consumers immediately # # @return [void] # # @api private def <<(obj) @target.call(obj) end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false
mattgreen/elevate
https://github.com/mattgreen/elevate/blob/edb3e428c9643974cdf1a747ff961c09d771aec5/lib/elevate/future.rb
lib/elevate/future.rb
module Elevate class Future OUTSTANDING = 0 FULFILLED = 1 def initialize @lock = NSConditionLock.alloc.initWithCondition(OUTSTANDING) @value = nil end def fulfill(value) if @lock.tryLockWhenCondition(OUTSTANDING) @value = value @lock.unlockWithCondition(FULFILLED) end end def value value = nil @lock.lockWhenCondition(FULFILLED) value = @value @lock.unlockWithCondition(FULFILLED) value end end end
ruby
MIT
edb3e428c9643974cdf1a747ff961c09d771aec5
2026-01-04T17:55:16.391428Z
false