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
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/config/file_loader_spec.rb
spec/circuitry/config/file_loader_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Config::FileLoader do subject { described_class } describe '.load' do context 'with valid fixture' do before do subject.load('spec/support/fixtures/example_config.yml.erb', 'test') end it 'loads publisher config' do expect(Circuitry.subscriber_config.queue_name).to eql('app-production-queuename') end it 'loads aws settings' do expect(Circuitry.subscriber_config.aws_options).to eql( access_key_id: 'test_access_key', secret_access_key: 'test_secret_key', region: 'us-east-1' ) end it 'coerces integers' do expect(Circuitry.subscriber_config.max_receive_count).to eql(4) end end context 'with invalid fixture' do it 'raises ConfigError' do expect { subject.load('spec/support/fixtures/invalid_config.yml', 'test') }.to raise_error(Circuitry::ConfigError) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/config/publisher_settings_spec.rb
spec/circuitry/config/publisher_settings_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Config::PublisherSettings do describe '.new' do context 'initialized with a hash' do subject { described_class.new(secret_key: '123', region: 'us-west-1') } it 'is configured' do expect(subject.secret_key).to eql('123') end end end describe '#async_strategy=' do it_behaves_like 'a validated setting', Circuitry::Publisher.async_strategies, :async_strategy end describe '#aws_options' do before do subject.access_key = 'access_key' subject.secret_key = 'secret_key' subject.region = 'region' end it 'returns a hash of AWS connection options' do expect(subject.aws_options).to eq(access_key_id: 'access_key', secret_access_key: 'secret_key', region: 'region') end context 'with overrides' do before do subject.aws_options_overrides = { endpoint: 'http://localhost:4566' } end it 'includes the overrides in AWS connection options hash' do expect(subject.aws_options).to eq(access_key_id: 'access_key', secret_access_key: 'secret_key', region: 'region', endpoint: 'http://localhost:4566') end end end describe '#middleware' do it_behaves_like 'middleware settings' end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/config/subscriber_settings_spec.rb
spec/circuitry/config/subscriber_settings_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Config::SubscriberSettings do describe '#async_strategy=' do it_behaves_like 'a validated setting', Circuitry::Subscriber.async_strategies, :async_strategy end describe '#queue_name' do it 'sets #dead_letter_queue_name' do expect { subject.queue_name = 'awesome' }.to change(subject, :dead_letter_queue_name).to('awesome-failures') end context 'dead_letter_queue_name is set' do before do subject.dead_letter_queue_name = 'dawson' end it 'does not set #dead_letter_queue_name' do expect { subject.queue_name = 'awesome' }.to_not change(subject, :dead_letter_queue_name) end end end describe '#aws_options' do before do subject.access_key = 'access_key' subject.secret_key = 'secret_key' subject.region = 'region' end it 'returns a hash of AWS connection options' do expect(subject.aws_options).to eq(access_key_id: 'access_key', secret_access_key: 'secret_key', region: 'region') end context 'with overrides' do before do subject.aws_options_overrides = { endpoint: 'http://localhost:4566' } end it 'includes the overrides in AWS connection options hash' do expect(subject.aws_options).to eq(access_key_id: 'access_key', secret_access_key: 'secret_key', region: 'region', endpoint: 'http://localhost:4566') end end end describe '#middleware' do it_behaves_like 'middleware settings' end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/processors/batcher_spec.rb
spec/circuitry/processors/batcher_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Processors::Batcher, type: :model do subject { described_class } it { is_expected.to be_a Circuitry::Processor } describe '.batch' do let(:pool) { double('Array', '<<' => []) } let(:block) { -> {} } before do allow(subject).to receive(:pool).and_return(pool) end it 'adds the block to the pool' do subject.process(&block) expect(pool).to have_received(:<<).with(block) end end describe '.flush' do let(:pool) { [-> {}, -> {}] } before do allow(subject).to receive(:pool).and_return(pool) end it 'calls each block' do subject.flush pool.each { |block| expect(block).to have_received(:call) } end it 'clears the pool' do subject.flush expect(pool).to be_empty end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/processors/threader_spec.rb
spec/circuitry/processors/threader_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Processors::Threader, type: :model do subject { described_class } it { is_expected.to be_a Circuitry::Processor } it_behaves_like 'an asyncronous processor' describe '.process' do let(:pool) { double('Array', '<<': []) } let(:block) { ->{ } } let(:thread) { double('Thread', join: true) } before do allow(subject).to receive(:pool).and_return(pool) allow(Thread).to receive(:new).and_return(thread) end it 'wraps the block in a thread' do subject.process(&block) expect(Thread).to have_received(:new).with(no_args, &block) end it 'adds the thread to the pool' do subject.process(&block) expect(pool).to have_received(:<<).with(thread) end end describe '.flush' do let(:pool) { [double('Thread', join: true), double('Thread', join: true)] } before do allow(subject).to receive(:pool).and_return(pool) end it 'joins each thread' do subject.flush pool.each { |thread| expect(thread).to have_received(:join) } end it 'clears the pool' do subject.flush expect(pool).to be_empty end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/processors/forker_spec.rb
spec/circuitry/processors/forker_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Processors::Forker, type: :model do subject { described_class } it { is_expected.to be_a Circuitry::Processor } it_behaves_like 'an asyncronous processor' describe '.fork' do before do allow(subject).to receive(:fork).and_return(pid) allow(Process).to receive(:detach) end let(:pid) { 'pid' } let(:block) { ->{ } } it 'forks a process' do subject.process(&block) expect(subject).to have_received(:fork) end it 'detaches the forked process' do subject.process(&block) expect(Process).to have_received(:detach).with(pid) end end describe '.flush' do it 'does nothing' do expect { subject.flush }.to_not raise_error end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry.rb
lib/circuitry.rb
require 'circuitry/railtie' if defined?(Rails) && Rails::VERSION::MAJOR >= 3 require 'circuitry/config/publisher_settings' require 'circuitry/config/subscriber_settings' require 'circuitry/locks/base' require 'circuitry/locks/memcache' require 'circuitry/locks/memory' require 'circuitry/locks/noop' require 'circuitry/locks/redis' require 'circuitry/middleware/chain' require 'circuitry/processor' require 'circuitry/processors/batcher' require 'circuitry/processors/forker' require 'circuitry/processors/threader' require 'circuitry/publisher' require 'circuitry/subscriber' require 'circuitry/version' module Circuitry class << self def subscriber_config @sub_config ||= Config::SubscriberSettings.new yield @sub_config if block_given? @sub_config end def subscriber_config=(options) @sub_config = Config::SubscriberSettings.new(options) end def publisher_config @pub_config ||= Config::PublisherSettings.new yield @pub_config if block_given? @pub_config end def publisher_config=(options) @pub_config = Config::PublisherSettings.new(options) end def publish(topic_name, object, options = {}) Publisher.new(options).publish(topic_name, object) end def subscribe(options = {}, &block) Subscriber.new(options).subscribe(&block) end def flush Processors.constants.each do |const| Processors.const_get(const).flush end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/version.rb
lib/circuitry/version.rb
module Circuitry VERSION = '3.5.0' end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/topic.rb
lib/circuitry/topic.rb
require 'circuitry/services/sns' module Circuitry class Topic class Finder include Services::SNS def initialize(name) self.name = name end def find sns.create_topic(name: name) end private attr_accessor :name end attr_reader :arn def initialize(arn) @arn = arn end def self.find(name) new(Finder.new(name).find.topic_arn) end def name @name ||= arn.split(':').last end def ==(other) other.hash == hash end def hash [self.class, arn].hash end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/processor.rb
lib/circuitry/processor.rb
module Circuitry module Processor def process(&_block) raise NotImplementedError, "#{self} must implement class method `process`" end def flush raise NotImplementedError, "#{self} must implement class method `flush`" end def on_exit Circuitry.subscriber_config.on_async_exit end protected def safely_process yield rescue => e logger.error("Error handling message: #{e}") error_handler.call(e) if error_handler end def pool @pool ||= [] end private def logger Circuitry.subscriber_config.logger end def error_handler Circuitry.subscriber_config.error_handler end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/publisher.rb
lib/circuitry/publisher.rb
require 'json' require 'timeout' require 'circuitry/concerns/async' require 'circuitry/services/sns' module Circuitry class PublishError < StandardError; end class SnsPublishError < StandardError def initialize(topic:, message:, exception:) msg = { error: "#{exception.class}: #{exception.message}", topic_arn: topic.arn, message: message } super msg.to_json end end class Publisher include Concerns::Async include Services::SNS DEFAULT_OPTIONS = { async: false, timeout: 15 }.freeze CONNECTION_ERRORS = [ ::Seahorse::Client::NetworkingError, ::Aws::SNS::Errors::InternalFailure ].freeze attr_reader :timeout def initialize(options = {}) options = DEFAULT_OPTIONS.merge(options) self.async = options[:async] self.timeout = options[:timeout] end def publish(topic_name, object) raise ArgumentError, 'topic_name cannot be nil' if topic_name.nil? raise ArgumentError, 'object cannot be nil' if object.nil? raise PublishError, 'AWS configuration is not set' unless can_publish? message = object.to_json if async? process_asynchronously { publish_message(topic_name, message) } else publish_message(topic_name, message) end end def self.default_async_strategy Circuitry.publisher_config.async_strategy end protected def publish_message(topic_name, message) middleware.invoke(topic_name, message) do # TODO: Don't use ruby timeout. # http://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/ Timeout.timeout(timeout) do logger.debug("Publishing message to #{topic_name}") handler = ->(error, attempt_number, _total_delay) do logger.warn("Error publishing attempt ##{attempt_number}: #{error.class} (#{error.message}); retrying...") end with_retries(max_tries: 3, handler: handler, rescue: CONNECTION_ERRORS, base_sleep_seconds: 0.05, max_sleep_seconds: 0.25) do topic = Topic.find(topic_name) sns_publish(topic: topic, message: message) end end end end attr_writer :timeout private def sns_publish(topic:, message:) sns.publish(topic_arn: topic.arn, message: message) rescue Aws::SNS::Errors::InvalidParameter => ex raise SnsPublishError.new(topic: topic, message: message, exception: ex) end def logger Circuitry.publisher_config.logger end def can_publish? return true if Circuitry.publisher_config.use_iam_profile Circuitry.publisher_config.aws_options.values.all? do |value| !value.nil? && !value.empty? end end def middleware Circuitry.publisher_config.middleware end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/queue.rb
lib/circuitry/queue.rb
require 'circuitry/services/sqs' module Circuitry class Queue include Services::SQS class Finder include Services::SQS def initialize(name) self.name = name end def find sqs.get_queue_url(queue_name: name) end private attr_accessor :name end attr_reader :url def initialize(url) self.url = url end def self.find(name) new(Finder.new(name).find.queue_url) end def name url.split('/').last end def arn @arn ||= attribute('QueueArn') end def attribute(name) sqs.get_queue_attributes(queue_url: url, attribute_names: [name]).attributes[name] end private attr_writer :url end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/railtie.rb
lib/circuitry/railtie.rb
require 'rails' require 'circuitry/config/file_loader' module Circuitry class Railtie < Rails::Railtie rake_tasks do load 'circuitry/tasks.rb' end initializer 'circuitry' do env = ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' %w[config/circuitry.yml.erb config/circuitry.yml].detect do |filename| Circuitry::Config::FileLoader.load(filename, env) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/message.rb
lib/circuitry/message.rb
require 'json' require 'circuitry/topic' module Circuitry class Message attr_reader :sqs_message def initialize(sqs_message) @sqs_message = sqs_message end def context @context ||= JSON.parse(sqs_message.body) end def body @body ||= JSON.parse(context['Message'], quirks_mode: true) end def topic @topic ||= Topic.new(context['TopicArn']) end def id sqs_message.message_id end def receipt_handle sqs_message.receipt_handle end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/subscriber.rb
lib/circuitry/subscriber.rb
require 'retries' require 'timeout' require 'circuitry/concerns/async' require 'circuitry/services/sqs' require 'circuitry/message' require 'circuitry/queue' module Circuitry class SubscribeError < StandardError; end class Subscriber include Concerns::Async include Services::SQS attr_reader :queue, :timeout, :wait_time, :batch_size, :lock DEFAULT_OPTIONS = { lock: true, async: false, timeout: 15, wait_time: 10, batch_size: 10 }.freeze CONNECTION_ERRORS = [ Aws::SQS::Errors::ServiceError ].freeze def initialize(options = {}) options = DEFAULT_OPTIONS.merge(options) self.subscribed = false self.queue = Queue.find(Circuitry.subscriber_config.queue_name).url %i[lock async timeout wait_time batch_size].each do |sym| send(:"#{sym}=", options[sym]) end trap_signals end def subscribe(&block) raise ArgumentError, 'block required' if block.nil? raise SubscribeError, 'AWS configuration is not set' unless can_subscribe? logger.info("Subscribing to queue: #{queue}") self.subscribed = true poll(&block) self.subscribed = false logger.info("Unsubscribed from queue: #{queue}") rescue *CONNECTION_ERRORS => e logger.error("Connection error to queue: #{queue}: #{e}") raise SubscribeError, e.message end def subscribed? subscribed end def self.async_strategies super - [:batch] end def self.default_async_strategy Circuitry.subscriber_config.async_strategy end protected attr_writer :queue, :timeout, :wait_time, :batch_size attr_accessor :subscribed def lock=(value) value = case value when true then Circuitry.subscriber_config.lock_strategy when false then Circuitry::Locks::NOOP.new when Circuitry::Locks::Base then value else raise ArgumentError, lock_value_error(value) end @lock = value end private def lock_value_error(value) opts = Circuitry::Locks::Base "Invalid value `#{value}`, must be one of `true`, `false`, or instance of `#{opts}`" end def trap_signals trap('SIGINT') do if subscribed? Thread.new { logger.info('Interrupt received, unsubscribing from queue...') } self.subscribed = false end end end def poll(&block) poller = Aws::SQS::QueuePoller.new(queue, client: sqs) poller.before_request do |_stats| throw :stop_polling unless subscribed? end poller.poll(max_number_of_messages: batch_size, wait_time_seconds: wait_time, skip_delete: true) do |messages| messages = [messages] unless messages.is_a?(Array) process_messages(Array(messages), &block) Circuitry.flush end end def process_messages(messages, &block) if async? process_messages_asynchronously(messages, &block) else process_messages_synchronously(messages, &block) end end def process_messages_asynchronously(messages, &block) messages.each { |message| process_asynchronously { process_message(message, &block) } } end def process_messages_synchronously(messages, &block) messages.each { |message| process_message(message, &block) } end def process_message(message, &block) message = Message.new(message) logger.debug("Processing message #{message.id}") handled = try_with_lock(message.id) do handle_message_with_middleware(message, &block) end logger.info("Ignoring duplicate message #{message.id}") unless handled rescue => e logger.error("Error processing message #{message.id}: #{e}") error_handler.call(e) if error_handler end def handle_message_with_middleware(message, &block) middleware.invoke(message.topic.name, message.body) do handle_message(message, &block) delete_message(message) end end def try_with_lock(id) if lock.soft_lock(id) begin yield rescue => e lock.unlock(id) raise e end lock.hard_lock(id) true else false end end # TODO: Don't use ruby timeout. # http://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/ def handle_message(message, &block) Timeout.timeout(timeout) do block.call(message.body, message.topic.name) end rescue => e logger.error("Error handling message #{message.id}: #{e}") raise e end def delete_message(message) logger.debug("Removing message #{message.id} from queue") sqs.delete_message(queue_url: queue, receipt_handle: message.receipt_handle) end def logger Circuitry.subscriber_config.logger end def error_handler Circuitry.subscriber_config.error_handler end def can_subscribe? return true if Circuitry.subscriber_config.use_iam_profile Circuitry.subscriber_config.aws_options.values.all? do |value| !value.nil? && !value.empty? end end def middleware Circuitry.subscriber_config.middleware end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/cli.rb
lib/circuitry/cli.rb
require 'circuitry/provisioning' require 'thor' module Circuitry class CLI < Thor class_option :verbose, aliases: :v, type: :boolean desc 'provision <queue> -t <topic> [<topic> ...]', <<-END Provision a queue subscribed to one or more topics END long_desc <<-END Creates an SQS queue with appropriate SNS access policy along with one or more SNS topics named <topic> that has an SQS subscription for each. When the queue already exists, its policy will be added or updated. When a topic already exists, it will be ignored. When a topic subscription already exists, it will be ignored. If no dead letter queue is specified, one will be created by default with the name <queue>-failures END option :topic_names, aliases: :t, type: :array, required: true option :access_key, aliases: :a, required: true option :secret_key, aliases: :s, required: true option :region, aliases: :r, required: true option :dead_letter_queue_name, aliases: :d option :visibility_timeout, aliases: :v, default: 30 * 60 option :max_receive_count, aliases: :n, default: 8 OPTIONS_KEYS_PUBLISHER_CONFIG = [:access_key, :secret_key, :region].freeze OPTIONS_KEYS_SUBSCRIBER_CONFIG = [:access_key, :secret_key, :region, :dead_letter_queue_name, :topic_names, :max_receive_count, :visibility_timeout].freeze def provision(queue_name) initialize_config(queue_name) logger = Logger.new(STDOUT) logger.level = Logger::INFO if options['verbose'] Circuitry::Provisioning.provision(logger: logger) end private def say(*args) puts(*args) if options['verbose'] end def initialize_config(queue_name) Circuitry.publisher_config.topic_names = [] Circuitry.subscriber_config.queue_name = queue_name assign_options_config end def assign_options_config OPTIONS_KEYS_PUBLISHER_CONFIG.each do |key| Circuitry.publisher_config.send(:"#{key}=", options[key.to_s]) end OPTIONS_KEYS_SUBSCRIBER_CONFIG.each do |key| Circuitry.subscriber_config.send(:"#{key}=", options[key.to_s]) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/tasks.rb
lib/circuitry/tasks.rb
namespace :circuitry do desc 'Create subscriber queues and subscribe queue to topics' task :setup do require 'logger' require 'circuitry/provisioning' logger = Logger.new(STDOUT) logger.level = Logger::INFO if Rake::Task.task_defined?(:environment) Rake::Task[:environment].invoke end Circuitry::Provisioning.provision(logger: logger) end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/provisioning.rb
lib/circuitry/provisioning.rb
require 'circuitry/provisioning/provisioner' module Circuitry module Provisioning def self.provision(logger: Logger.new(STDOUT)) Provisioning::Provisioner.new(logger).run end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/testing.rb
lib/circuitry/testing.rb
require 'circuitry' module Circuitry class Publisher def publish(_topic_name, _object) # noop end end class Subscriber def subscribe(&_block) # noop end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/services/sqs.rb
lib/circuitry/services/sqs.rb
require 'aws-sdk-sqs' module Circuitry module Services module SQS def sqs @sqs ||= Aws::SQS::Client.new(Circuitry.subscriber_config.aws_options) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/services/sns.rb
lib/circuitry/services/sns.rb
require 'aws-sdk-sns' module Circuitry module Services module SNS def sns @sns ||= Aws::SNS::Client.new(Circuitry.publisher_config.aws_options) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/concerns/async.rb
lib/circuitry/concerns/async.rb
require 'circuitry/processors/batcher' require 'circuitry/processors/forker' require 'circuitry/processors/threader' module Circuitry class NotSupportedError < StandardError; end module Concerns module Async attr_reader :async def self.included(base) base.extend(ClassMethods) end module ClassMethods def async_strategies [:fork, :thread, :batch] end def default_async_strategy raise NotImplementedError, "#{name} must implement class method `default_async_strategy`" end end def process_asynchronously(&block) send(:"process_via_#{async}", &block) end def async=(value) value = case value when false, nil then false when true then self.class.default_async_strategy when *self.class.async_strategies then value else raise ArgumentError, async_value_error(value) end if value == :fork && !platform_supports_forking? raise NotSupportedError, 'Your platform does not support forking' end @async = value end def async? ![nil, false].include?(async) end private def async_value_error(value) options = [true, false].concat(self.class.async_strategies).inspect "Invalid value `#{value.inspect}`, must be one of #{options}" end def platform_supports_forking? Process.respond_to?(:fork) end def process_via_fork(&block) Processors::Forker.process(&block) end def process_via_thread(&block) Processors::Threader.process(&block) end def process_via_batch(&block) Processors::Batcher.process(&block) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/provisioning/topic_creator.rb
lib/circuitry/provisioning/topic_creator.rb
require 'circuitry/services/sns' require 'circuitry/topic' module Circuitry module Provisioning class TopicCreator include Services::SNS attr_reader :topic_name def self.find_or_create(topic_name) new(topic_name).topic end def initialize(topic_name) self.topic_name = topic_name end def topic return @topic if defined?(@topic) response = sns.create_topic(name: topic_name) @topic = Topic.new(response.topic_arn) end private attr_writer :topic_name end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/provisioning/queue_creator.rb
lib/circuitry/provisioning/queue_creator.rb
require 'circuitry/services/sqs' require 'circuitry/queue' module Circuitry module Provisioning class QueueCreator include Services::SQS attr_reader :queue_name attr_reader :visibility_timeout def self.find_or_create(queue_name, dead_letter_queue_name: nil, max_receive_count: 8, visibility_timeout: 30 * 60) creator = new(queue_name, visibility_timeout) result = creator.create_queue creator.create_dead_letter_queue(dead_letter_queue_name, max_receive_count) if dead_letter_queue_name result end def initialize(queue_name, visibility_timeout) self.queue_name = queue_name self.visibility_timeout = visibility_timeout end def create_queue @queue ||= Queue.new(create_primary_queue_internal) end def create_dead_letter_queue(name, max_receive_count) @dl_queue ||= Queue.new(create_dl_queue_internal(name, max_receive_count)) end private attr_writer :queue_name attr_writer :visibility_timeout def create_dl_queue_internal(name, max_receive_count) dl_url = sqs.create_queue(queue_name: name).queue_url dl_arn = sqs.get_queue_attributes( queue_url: dl_url, attribute_names: ['QueueArn'] ).attributes['QueueArn'] policy = build_redrive_policy(dl_arn, max_receive_count) sqs.set_queue_attributes(queue_url: create_queue.url, attributes: policy) dl_url end def build_redrive_policy(deadletter_arn, max_receive_count) { 'RedrivePolicy' => %({"maxReceiveCount":"#{max_receive_count}", "deadLetterTargetArn":"#{deadletter_arn}"}) } end def create_primary_queue_internal attributes = { 'VisibilityTimeout' => visibility_timeout.to_s } sqs.create_queue(queue_name: queue_name, attributes: attributes).queue_url end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/provisioning/subscription_creator.rb
lib/circuitry/provisioning/subscription_creator.rb
require 'circuitry/services/sns' require 'circuitry/topic' module Circuitry module Provisioning class SubscriptionCreator include Services::SNS include Services::SQS attr_reader :queue attr_reader :topics def self.subscribe_all(queue, topics) new(queue, topics).subscribe_all end def initialize(queue, topics) raise ArgumentError, 'queue must be a Circuitry::Queue' unless queue.is_a?(Circuitry::Queue) raise ArgumentError, 'topics must be an array' unless topics.is_a?(Array) self.queue = queue self.topics = topics end def subscribe_all topics.each do |topic| sns.subscribe(topic_arn: topic.arn, endpoint: queue.arn, protocol: 'sqs') end if topics.any? sqs.set_queue_attributes(queue_url: queue.url, attributes: build_policy) end end private attr_writer :queue attr_writer :topics def build_policy # The aws ruby SDK doesn't have a policy builder :{ { 'Policy' => { 'Version' => '2012-10-17', 'Id' => "#{queue.arn}/SNSPolicy", 'Statement' => [build_policy_statement] }.to_json } end def build_policy_statement { 'Sid' => "Sid-#{queue.name}-subscriptions", 'Effect' => 'Allow', 'Principal' => { 'AWS' => '*' }, 'Action' => 'SQS:SendMessage', 'Resource' => queue.arn, 'Condition' => { 'ForAnyValue:ArnEquals' => { 'aws:SourceArn' => topics.map(&:arn) } } } end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/provisioning/provisioner.rb
lib/circuitry/provisioning/provisioner.rb
require 'circuitry' require 'circuitry/provisioning/queue_creator' require 'circuitry/provisioning/topic_creator' require 'circuitry/provisioning/subscription_creator' module Circuitry module Provisioning class Provisioner def initialize(logger) self.logger = logger end def run queue = create_queue subscribe_topics(queue, create_topics(:subscriber, subscriber_config.topic_names)) if queue create_topics(:publisher, publisher_config.topic_names) end private attr_accessor :logger def publisher_config Circuitry.publisher_config end def subscriber_config Circuitry.subscriber_config end def create_queue if subscriber_config.queue_name.nil? logger.info 'Skipping queue creation: queue_name is not configured' return nil end safe_aws('Create queue') do queue = QueueCreator.find_or_create( subscriber_config.queue_name, dead_letter_queue_name: subscriber_config.dead_letter_queue_name, max_receive_count: subscriber_config.max_receive_count, visibility_timeout: subscriber_config.visibility_timeout ) logger.info "Created queue #{queue.url}" queue end end def create_topics(type, topics) safe_aws("Create #{type.to_s} topics") do topics.map do |topic_name| topic = TopicCreator.find_or_create(topic_name) logger.info "Created topic #{topic.name}" topic end end end def subscribe_topics(queue, topics) safe_aws('Subscribe to topics') do SubscriptionCreator.subscribe_all(queue, topics) plural_form = topics.size == 1 ? '' : 's' logger.info "Subscribed #{topics.size} topic#{plural_form} to #{queue.name}" true end end def safe_aws(desc) yield rescue Aws::SQS::Errors::AccessDenied logger.fatal("#{desc}: Access denied. Check your configured credentials.") nil end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/middleware/entry.rb
lib/circuitry/middleware/entry.rb
module Circuitry module Middleware class Entry attr_reader :klass, :args def initialize(klass, *args) self.klass = klass self.args = args end def build klass.new(*args) end private attr_writer :klass, :args end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/middleware/chain.rb
lib/circuitry/middleware/chain.rb
require 'circuitry/middleware/entry' module Circuitry module Middleware class Chain include Enumerable def initialize yield self if block_given? end def each(&block) entries.each(&block) end def entries @entries ||= [] end def add(klass, *args) remove(klass) if exists?(klass) entries << Entry.new(klass, *args) end def remove(klass) entries.delete_if { |entry| entry.klass == klass } end def prepend(klass, *args) remove(klass) if exists?(klass) entries.unshift(Entry.new(klass, *args)) end def insert_before(old_klass, new_klass, *args) new_entry = build_or_replace_entry(new_klass, *args) i = entries.index { |entry| entry.klass == old_klass } || 0 entries.insert(i, new_entry) end def insert_after(old_klass, new_klass, *args) new_entry = build_or_replace_entry(new_klass, *args) i = entries.index { |entry| entry.klass == old_klass } || entries.size - 1 entries.insert(i + 1, new_entry) end def exists?(klass) any? { |entry| entry.klass == klass } end def build map(&:build) end def clear entries.clear end def invoke(*args) chain = build.dup traverse_chain = lambda do if chain.empty? yield else chain.shift.call(*args, &traverse_chain) end end traverse_chain.call end private def build_or_replace_entry(klass, *args) i = entries.index { |entry| entry.klass == klass } entry = i.nil? ? Entry.new(klass, *args) : entries.delete_at(i) if entry.args == args entry else Entry.new(klass, *args) end end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/locks/memory.rb
lib/circuitry/locks/memory.rb
module Circuitry module Locks class Memory include Base class << self def store @store ||= {} end def semaphore @semaphore ||= Mutex.new end end protected def lock(key, ttl) reap store do |store| if store.key?(key) false else store[key] = Time.now + ttl true end end end def lock!(key, ttl) reap store do |store| store[key] = Time.now + ttl end end def unlock!(key) store do |store| store.delete(key) end end private def store semaphore.synchronize do yield self.class.store end end def reap store do |store| now = Time.now store.delete_if { |_, expires_at| expires_at <= now } end end def semaphore self.class.semaphore end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/locks/redis.rb
lib/circuitry/locks/redis.rb
module Circuitry module Locks class Redis include Base def initialize(options = {}) super(options) self.client = options.fetch(:client) do require 'redis' ::Redis.new(options) end end protected def lock(key, ttl) with_pool do |client| client.set(key, (Time.now + ttl).to_i, ex: ttl, nx: true) end end def lock!(key, ttl) with_pool do |client| client.set(key, (Time.now + ttl).to_i, ex: ttl) end end def unlock!(key) with_pool do |client| client.del(key) end end private attr_accessor :client def with_pool(&block) if pool? client.with(&block) else yield client end end def pool? defined?(ConnectionPool) && client.is_a?(ConnectionPool) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/locks/noop.rb
lib/circuitry/locks/noop.rb
module Circuitry module Locks class NOOP include Base protected def lock(_key, _ttl) true end def lock!(key, ttl) # do nothing end def unlock!(key) # do nothing end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/locks/memcache.rb
lib/circuitry/locks/memcache.rb
module Circuitry module Locks class Memcache include Base def initialize(options = {}) super(options) self.client = options.fetch(:client) do require 'dalli' ::Dalli::Client.new(options[:host], options) end end protected def lock(key, ttl) client.add(key, (Time.now + ttl).to_i, ttl) end def lock!(key, ttl) client.set(key, (Time.now + ttl).to_i, ttl) end def unlock!(key) client.delete(key) end private attr_accessor :client end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/locks/base.rb
lib/circuitry/locks/base.rb
module Circuitry module Locks module Base DEFAULT_SOFT_TTL = (5 * 60).freeze # 5 minutes DEFAULT_HARD_TTL = (24 * 60 * 60).freeze # 24 hours attr_reader :soft_ttl, :hard_ttl def initialize(options = {}) self.soft_ttl = options.fetch(:soft_ttl, DEFAULT_SOFT_TTL) self.hard_ttl = options.fetch(:hard_ttl, DEFAULT_HARD_TTL) end def soft_lock(id) lock(lock_key(id), soft_ttl) end def hard_lock(id) lock!(lock_key(id), hard_ttl) end def unlock(id) unlock!(lock_key(id)) end protected def lock(_key, _ttl) raise NotImplementedError end def lock!(_key, _ttl) raise NotImplementedError end def unlock!(_key) raise NotImplementedError end private attr_writer :soft_ttl, :hard_ttl def lock_key(id) "circuitry:lock:#{id}" end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/config/file_loader.rb
lib/circuitry/config/file_loader.rb
require 'yaml' require 'erb' require 'fileutils' module Circuitry module Config module FileLoader def self.load(cfile, environment = 'development') return nil unless File.exist?(cfile) opts = {} opts = YAML.load(ERB.new(IO.read(cfile)).result) || opts opts = opts.merge(opts.delete(environment) || {}) publisher_opts = opts.merge(opts.delete('publisher') || {}) subscriber_opts = opts.merge(opts.delete('subscriber') || {}) Circuitry.subscriber_config = subscriber_opts Circuitry.publisher_config = publisher_opts true end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/config/shared_settings.rb
lib/circuitry/config/shared_settings.rb
require 'logger' module Circuitry class ConfigError < StandardError; end module Config module SharedSettings def self.included(base) base.attribute :access_key, String base.attribute :secret_key, String base.attribute :region, String, default: 'us-east-1' base.attribute :use_iam_profile, Virtus::Attribute::Boolean, default: false base.attribute :logger, Logger, default: Logger.new(STDERR) base.attribute :error_handler base.attribute :topic_names, Array[String], default: [] base.attribute :on_async_exit base.attribute :async_strategy, Symbol, default: ->(_page, _att) { :fork } base.attribute :aws_options_overrides, Hash, default: {} end def middleware @middleware ||= Middleware::Chain.new yield @middleware if block_given? @middleware end def aws_options { access_key_id: access_key, secret_access_key: secret_key, region: region, **aws_options_overrides } end def validate_setting(value, permitted_values) return if permitted_values.include?(value) raise ConfigError, "invalid value `#{value}`, must be one of #{permitted_values.inspect}" end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/config/publisher_settings.rb
lib/circuitry/config/publisher_settings.rb
require 'virtus' require 'circuitry/config/shared_settings' module Circuitry module Config class PublisherSettings include Virtus::Model include SharedSettings def async_strategy=(value) validate_setting(value, Publisher.async_strategies) super end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/config/subscriber_settings.rb
lib/circuitry/config/subscriber_settings.rb
require 'virtus' require 'circuitry/config/shared_settings' module Circuitry module Config class SubscriberSettings include Virtus::Model include SharedSettings attribute :queue_name, String attribute :dead_letter_queue_name, String attribute :visibility_timeout, Integer, default: 30 * 60 attribute :max_receive_count, Integer, default: 8 attribute :lock_strategy, Object, default: ->(_page, _att) { Circuitry::Locks::Memory.new } def dead_letter_queue_name super || "#{queue_name}-failures" end def async_strategy=(value) validate_setting(value, Subscriber.async_strategies) super end def lock_strategy=(value) unless value.is_a?(Circuitry::Locks::Base) raise ConfigError, "invalid lock strategy \"#{value.inspect}\"" end super end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/processors/forker.rb
lib/circuitry/processors/forker.rb
require 'circuitry/processor' module Circuitry module Processors module Forker class << self include Processor def process(&block) pid = fork do safely_process(&block) on_exit.call if on_exit end Process.detach(pid) end def flush end end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/processors/batcher.rb
lib/circuitry/processors/batcher.rb
require 'circuitry/processor' module Circuitry module Processors module Batcher class << self include Processor def process(&block) raise ArgumentError, 'no block given' unless block_given? pool << block end def flush while (block = pool.shift) safely_process(&block) end end end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/lib/circuitry/processors/threader.rb
lib/circuitry/processors/threader.rb
require 'circuitry/processor' module Circuitry module Processors module Threader class << self include Processor def process(&block) raise ArgumentError, 'no block given' unless block_given? pool << Thread.new do safely_process(&block) on_exit.call if on_exit end end def flush pool.each(&:join) ensure pool.clear end end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/error_class_spec.rb
spec/error_class_spec.rb
require 'spec_helper' describe Contentful::Error do let(:r) { Contentful::Response.new raw_fixture('not_found', 404) } describe '#response' do it 'returns the response the error has been initialized with' do expect(Contentful::Error.new(r).response).to be r end end describe '#message' do it 'returns the message found in the response json' do message = "HTTP status code: 404\n"\ "Message: The resource could not be found.\n"\ "Details: {\"type\"\\s*=>\\s*\"Entry\", \"space\"\\s*=>\\s*\"cfexampleapi\", \"id\"\\s*=>\\s*\"not found\"}\n"\ "Request ID: 85f-351076632" expect(Contentful::Error.new(r).message).not_to be_nil expect(Contentful::Error.new(r).message).to match(Regexp.new(message)) end describe 'message types' do describe 'default messages' do it '400' do response = Contentful::Response.new raw_fixture('default_400', 400) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 400\n"\ "Message: The request was malformed or missing a required parameter.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '401' do response = Contentful::Response.new raw_fixture('default_401', 401) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 401\n"\ "Message: The authorization token was invalid.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '403' do response = Contentful::Response.new raw_fixture('default_403', 403) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 403\n"\ "Message: The specified token does not have access to the requested resource.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '404' do response = Contentful::Response.new raw_fixture('default_404', 404) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 404\n"\ "Message: The requested resource or endpoint could not be found.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '429' do response = Contentful::Response.new raw_fixture('default_429', 429) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 429\n"\ "Message: Rate limit exceeded. Too many requests.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '500' do response = Contentful::Response.new raw_fixture('default_500', 500) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 500\n"\ "Message: Internal server error.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '502' do response = Contentful::Response.new raw_fixture('default_502', 502) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 502\n"\ "Message: The requested space is hibernated.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it '503' do response = Contentful::Response.new raw_fixture('default_503', 503) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 503\n"\ "Message: The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end end describe 'special cases' do describe '400' do it 'details is a string' do response = Contentful::Response.new raw_fixture('400_details_string', 400) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 400\n"\ "Message: The request was malformed or missing a required parameter.\n"\ "Details: some error\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'details is an object, internal errors are strings' do response = Contentful::Response.new raw_fixture('400_details_errors_string', 400) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 400\n"\ "Message: The request was malformed or missing a required parameter.\n"\ "Details: some error\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'details is an object, internal errors are objects which have details' do response = Contentful::Response.new raw_fixture('400_details_errors_object', 400) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 400\n"\ "Message: The request was malformed or missing a required parameter.\n"\ "Details: some error\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end end describe '403' do it 'has an array of reasons' do response = Contentful::Response.new raw_fixture('403_reasons', 403) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 403\n"\ "Message: The specified token does not have access to the requested resource.\n"\ "Details: \n\tReasons:\n"\ "\t\tfoo\n"\ "\t\tbar\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end end describe '404' do it 'details is a string' do response = Contentful::Response.new raw_fixture('404_details_string', 404) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 404\n"\ "Message: The requested resource or endpoint could not be found.\n"\ "Details: The resource could not be found\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end describe 'has a type' do it 'type is on the top level' do response = Contentful::Response.new raw_fixture('404_type', 404) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 404\n"\ "Message: The requested resource or endpoint could not be found.\n"\ "Details: The requested Asset could not be found.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'type is not on the top level' do response = Contentful::Response.new raw_fixture('404_sys_type', 404) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 404\n"\ "Message: The requested resource or endpoint could not be found.\n"\ "Details: The requested Space could not be found.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end end it 'can specify the resource id' do response = Contentful::Response.new raw_fixture('404_id', 404) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 404\n"\ "Message: The requested resource or endpoint could not be found.\n"\ "Details: The requested Asset could not be found. ID: foobar.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end end describe '429' do it 'can show the time until reset' do response = Contentful::Response.new raw_fixture('default_429', 429, false, {'x-contentful-ratelimit-reset' => 60}) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 429\n"\ "Message: Rate limit exceeded. Too many requests.\n"\ "Request ID: 85f-351076632\n"\ "Time until reset (seconds): 60" expect(error.message).to eq message end end end describe 'generic error' do it 'with everything' do response = Contentful::Response.new raw_fixture('other_error', 512) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 512\n"\ "Message: Some error occurred.\n"\ "Details: some text\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'no details' do response = Contentful::Response.new raw_fixture('other_error_no_details', 512) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 512\n"\ "Message: Some error occurred.\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'no request id' do response = Contentful::Response.new raw_fixture('other_error_no_request_id', 512) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 512\n"\ "Message: Some error occurred.\n"\ "Details: some text" expect(error.message).to eq message end it 'no message' do response = Contentful::Response.new raw_fixture('other_error_no_message', 512) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 512\n"\ "Message: The following error was received: {\n"\ " \"sys\": {\n"\ " \"type\": \"Error\",\n"\ " \"id\": \"SomeError\"\n"\ " },\n"\ " \"details\": \"some text\",\n"\ " \"requestId\": \"85f-351076632\"\n"\ "}\n"\ "\n"\ "Details: some text\n"\ "Request ID: 85f-351076632" expect(error.message).to eq message end it 'nothing' do response = Contentful::Response.new raw_fixture('other_error_nothing', 512) error = Contentful::Error[response.raw.status].new(response) message = "HTTP status code: 512\n"\ "Message: The following error was received: {\n"\ " \"sys\": {\n"\ " \"type\": \"Error\",\n"\ " \"id\": \"SomeError\"\n"\ " }\n"\ "}\n" expect(error.message).to eq message end end end end describe Contentful::UnparsableJson do describe '#message' do it 'returns the json parser\'s message' do uj = Contentful::Response.new raw_fixture('unparsable') expect(Contentful::UnparsableJson.new(uj).message).to \ include "expected ',' or '}' after object value" end end end describe '.[]' do it 'returns BadRequest error class for 400' do expect(Contentful::Error[400]).to eq Contentful::BadRequest end it 'returns Unauthorized error class for 401' do expect(Contentful::Error[401]).to eq Contentful::Unauthorized end it 'returns AccessDenied error class for 403' do expect(Contentful::Error[403]).to eq Contentful::AccessDenied end it 'returns NotFound error class for 404' do expect(Contentful::Error[404]).to eq Contentful::NotFound end it 'returns ServerError error class for 500' do expect(Contentful::Error[500]).to eq Contentful::ServerError end it 'returns ServiceUnavailable error class for 503' do expect(Contentful::Error[503]).to eq Contentful::ServiceUnavailable end it 'returns generic error class for any other value' do expect(Contentful::Error[nil]).to eq Contentful::Error expect(Contentful::Error[200]).to eq Contentful::Error end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/file_spec.rb
spec/file_spec.rb
require 'spec_helper' describe Contentful::File do let(:file) { vcr('asset') { create_client.asset('nyancat').file } } describe 'Properties' do it 'has #file_name' do expect(file.file_name).to eq 'Nyan_cat_250px_frame.png' end it 'has #content_type' do expect(file.content_type).to eq 'image/png' end it 'has #url' do expect(file.url).to eq '//images.contentful.com/cfexampleapi/4gp6taAwW4CmSgumq2ekUm/9da0cd1936871b8d72343e895a00d611/Nyan_cat_250px_frame.png' end it 'has #details' do expect(file.details).to be_instance_of Hash end end describe 'camel case' do it 'supports camel case' do vcr('asset') { file = create_client(use_camel_case: true).asset('nyancat').file expect(file.contentType).to eq 'image/png' expect(file.fileName).to eq 'Nyan_cat_250px_frame.png' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/deleted_asset_spec.rb
spec/deleted_asset_spec.rb
require 'spec_helper' describe 'DeletedAsset' do let(:deleted_asset)do vcr('sync_deleted_asset')do create_client.sync(initial: true, type: 'DeletedAsset').first_page.items[0] end end describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(deleted_asset.sys).to be_a Hash expect(deleted_asset.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(deleted_asset.id).to eq '5c6VY0gWg0gwaIeYkUUiqG' end it 'has #type' do expect(deleted_asset.type).to eq 'DeletedAsset' end it 'has #deleted_at' do expect(deleted_asset.created_at).to be_a DateTime end end describe 'camel case' do it 'supports camel case' do vcr('sync_deleted_asset') { deleted_asset = create_client(use_camel_case: true).sync(initial: true, type: 'DeletedAsset').first_page.items[0] expect(deleted_asset.createdAt).to be_a DateTime } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/response_spec.rb
spec/response_spec.rb
require 'spec_helper' describe Contentful::Response do let(:successful_response) { Contentful::Response.new raw_fixture('nyancat'), Contentful::Request.new(nil, '/entries', nil, 'nyancat') } let(:error_response) { Contentful::Response.new raw_fixture('not_found', 404) } let(:unparsable_response) { Contentful::Response.new raw_fixture('unparsable') } describe '#raw' do it 'returns the raw response it has been initalized with' do expect(successful_response.raw.to_s).to eql raw_fixture('nyancat').to_s end end describe '#object' do it "returns the repsonse's parsed json" do expect(successful_response.object).to eq json_fixture('nyancat') end end describe '#request' do it 'returns the request the response has been initalized with' do expect(successful_response.request).to be_a Contentful::Request end end describe '#status' do it 'returns :ok for normal responses' do expect(successful_response.status).to eq :ok end it 'returns :error for error responses' do expect(error_response.status).to eq :error end it 'returns :error for unparsable json responses' do expect(unparsable_response.status).to eq :error end it 'returns :error for responses without content' do raw_response = '' allow(raw_response).to receive(:status) { 204 } no_content_response = Contentful::Response.new raw_response expect(no_content_response.status).to eq :no_content end end describe '#error_message' do it 'returns contentful error message for contentful errors' do expect(error_response.error_message).to eq 'The resource could not be found.' end it 'returns json parser error message for json parse errors' do expect(unparsable_response.error_message).to include "expected ',' or '}' after object value" end it 'returns a ServiceUnavailable error on a 503' do error_response = Contentful::Response.new raw_fixture('not_found', 503) expect(error_response.status).to eql :error expect(error_response.object).to be_kind_of Contentful::ServiceUnavailable end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/request_spec.rb
spec/request_spec.rb
require 'spec_helper' describe Contentful::Request do describe '#get' do it 'calls client' do client = create_client request = Contentful::Request.new(client, '/content_types', nil, 'nyancat') expect(client).to receive(:get).with(request) request.get end end describe '#query' do it 'converts arrays given in query to comma strings' do client = create_client request = Contentful::Request.new(client, '/entries', 'fields.likes[in]' => %w(jake finn)) expect(request.query[:'fields.likes[in]']).to eq 'jake,finn' end end context '[single resource]' do let(:request)do Contentful::Request.new(create_client, '/content_types', nil, 'nyancat') end describe '#url' do it 'contais endpoint' do expect(request.url).to include 'content_types' end it 'contains id' do expect(request.url).to include 'nyancat' end end end context '[multi resource]' do let(:request)do Contentful::Request.new(create_client, '/content_types', 'something' => 'requested') end describe '#query' do it 'contains query' do expect(request.query).not_to be_empty expect(request.query[:something]).to eq 'requested' end end describe '#url' do it 'contais endpoint' do expect(request.url).to include 'content_types' end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/client_class_spec.rb
spec/client_class_spec.rb
require 'spec_helper' describe Contentful::Client do describe '#get' do let(:client) { create_client() } let(:proxy_client) { create_client(proxy_host: '183.207.232.194', proxy_port: 8080, secure: false) } let(:timeout_client) { create_client(timeout_connect: 1, timeout_read: 2, timeout_write: 3) } let(:request) { Contentful::Request.new(nil, client.environment_url('/content_types'), nil, 'cat') } it 'uses #base_url' do expect(client).to receive(:base_url).and_call_original vcr('content_type') { client.get(request) } end it 'uses #request_headers' do expect(client).to receive(:request_headers).and_call_original vcr('content_type') { client.get(request) } end it 'uses Request#url' do expect(request).to receive(:url).and_call_original vcr('content_type') { client.get(request) } end it 'uses Request#query' do expect(request).to receive(:query).thrice.and_call_original vcr('content_type') { client.get(request) } end it 'calls #get_http' do expect(client.class).to receive(:get_http).with(client.base_url + request.url, request.query, client.request_headers, client.proxy_params, client.timeout_params, nil) { raw_fixture('content_type') } client.get(request) end it 'calls #get_http via proxy' do expect(proxy_client.class).to receive(:get_http).with(proxy_client.base_url + request.url, request.query, proxy_client.request_headers, proxy_client.proxy_params, client.timeout_params, nil) { raw_fixture('content_type') } proxy_client.get(request) expect(proxy_client.proxy_params[:host]).to eq '183.207.232.194' expect(proxy_client.proxy_params[:port]).to eq 8080 end describe 'timeout params' do context 'with timeouts configured' do it 'calls #get_http with timeouts' do expect(timeout_client.class).to receive(:get_http).with(timeout_client.base_url + request.url, request.query, timeout_client.request_headers, timeout_client.proxy_params, timeout_client.timeout_params, nil) { raw_fixture('content_type') } timeout_client.get(request) expect(timeout_client.timeout_params[:connect]).to eq 1 expect(timeout_client.timeout_params[:read]).to eq 2 expect(timeout_client.timeout_params[:write]).to eq 3 end end context 'without timeouts' do it 'calls #get_http with timeouts' do expect(client.class).to receive(:get_http).with(client.base_url + request.url, request.query, client.request_headers, client.proxy_params, client.timeout_params, nil) { raw_fixture('content_type') } client.get(request) expect(client.timeout_params).to eq({}) end end end describe 'build_resources parameter' do it 'returns Contentful::Resource object if second parameter is true [default]' do res = vcr('content_type') { client.get(request) } expect(res).to be_a Contentful::BaseResource end it 'returns a Contentful::Response object if second parameter is not true' do res = vcr('content_type') { client.get(request, false) } expect(res).to be_a Contentful::Response end end describe 'instrumenter' do before do test_instrumenter = Class.new(HTTP::Features::Instrumentation::NullInstrumenter) do attr_reader :output def initialize @output = {} end def start(_name, payload) output[:start] = payload end def finish(_name, payload) output[:finish] = payload end end stub_const("TestInstrumenter", test_instrumenter) end context "when an instrumenter is given to client" do let(:instrumenter) { TestInstrumenter.new } let(:instrumented_client) { create_client(http_instrumenter: instrumenter) } it 'calls #get_http with TestInstrumenter' do expect(instrumented_client.configuration[:http_instrumenter]).to eq instrumenter expect(instrumented_client.class).to receive(:get_http).with(instrumented_client.base_url + request.url, request.query, instrumented_client.request_headers, instrumented_client.proxy_params, instrumented_client.timeout_params, instrumenter) { raw_fixture('content_type') } instrumented_client.get(request) end end end end describe '#sync' do it 'creates a new Sync object' do expect(create_client.sync).to be_a Contentful::Sync end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/entry_spec.rb
spec/entry_spec.rb
require 'spec_helper' describe Contentful::Entry do let(:entry) { vcr('entry') { create_client.entry 'nyancat' } } let(:subclass) do Class.new(described_class) do # An overridden sys method: def created_at; 'yesterday'; end # An overridden field method: def best_friend; 'octocat'; end end end let(:raw) { entry.raw } let(:subclassed_entry) { subclass.new(raw, create_client.configuration) } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(entry.sys).to be_a Hash expect(entry.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(entry.id).to eq 'nyancat' end it 'has #type' do expect(entry.type).to eq 'Entry' end it 'has #space' do expect(entry.space).to be_a Contentful::Link end it 'has #content_type' do expect(entry.content_type).to be_a Contentful::Link end it 'has #created_at' do expect(entry.created_at).to be_a DateTime end it 'has #updated_at' do expect(entry.updated_at).to be_a DateTime end it 'has #revision' do expect(entry.revision).to eq 5 end context 'when subclassed' do it 'does not redefine existing methods' do expect(subclassed_entry.created_at).to eq 'yesterday' end end end describe 'Fields' do it 'has a #fields getter returning a hash with symbol keys' do expect(entry.sys).to be_a Hash expect(entry.sys.keys.sample).to be_a Symbol end it "contains the entry's fields" do expect(entry.fields[:color]).to eq 'rainbow' expect(entry.fields[:best_friend]).to be_a Contentful::Entry end context 'when subclassed' do it 'does not redefine existing methods' do expect(subclassed_entry.best_friend).to eq 'octocat' end end end describe 'multiple locales' do it 'can handle multiple locales' do vcr('entry_locales') { nyancat = create_client.entries(locale: "*", 'sys.id' => 'nyancat').items.first expect(nyancat.fields('en-US')[:name]).to eq "Nyan Cat" expect(nyancat.fields('tlh')[:name]).to eq "Nyan vIghro'" expect(nyancat.fields(:'en-US')[:name]).to eq "Nyan Cat" expect(nyancat.fields(:tlh)[:name]).to eq "Nyan vIghro'" } end describe '#fields_with_locales' do it 'can handle entries with just 1 locale' do vcr('entry') { nyancat = create_client.entry('nyancat') expect(nyancat.fields_with_locales[:name].size).to eq(1) expect(nyancat.fields_with_locales[:name][:'en-US']).to eq("Nyan Cat") } end it 'can handle entries with multiple locales' do vcr('entry_locales') { nyancat = create_client.entries(locale: "*", 'sys.id' => 'nyancat').items.first expect(nyancat.fields_with_locales[:name].size).to eq(2) expect(nyancat.fields_with_locales[:name][:'en-US']).to eq("Nyan Cat") expect(nyancat.fields_with_locales[:name][:tlh]).to eq("Nyan vIghro'") } end it 'can have references in multiple locales and they are properly solved' do vcr('multi_locale_reference') { client = create_client( space: '1sjfpsn7l90g', access_token: 'e451a3cdfced9000220be41ed9c899866e8d52aa430eaf7c35b09df8fc6326f9', dynamic_entries: :auto ) entry = client.entries(locale: '*').first expect(entry.image).to be_a ::Contentful::Asset expect(entry.fields('zh')[:image]).to be_a ::Contentful::Asset expect(entry.fields('es')[:image]).to be_a ::Contentful::Asset expect(entry.image.id).not_to eq entry.fields('zh')[:image].id } end it 'can have references with arrays in multiple locales and have them properly solved' do vcr('multi_locale_array_reference') { client = create_client( space: 'cma9f9g4dxvs', access_token: '3e4560614990c9ac47343b9eea762bdaaebd845766f619660d7230787fd545e1', dynamic_entries: :auto ) entry = client.entries(content_type: 'test', locale: '*').first expect(entry.files).to be_a ::Array expect(entry.references).to be_a ::Array expect(entry.files.first).to be_a ::Contentful::Asset expect(entry.references.first.entry?).to be_truthy expect(entry.fields('zh')[:files]).to be_a ::Array expect(entry.fields('zh')[:references]).to be_a ::Array expect(entry.fields('zh')[:files].first).to be_a ::Contentful::Asset expect(entry.fields('zh')[:references].first.entry?).to be_truthy expect(entry.files.first.id).not_to eq entry.fields('zh')[:files].first.id } end end end it '#raw' do vcr('entry/raw') { nyancat = create_client.entry('nyancat') expect(nyancat.raw).to eq(create_client(raw_mode: true).entry('nyancat').object['items'].first) } end it '#raw_with_links does not modify original raw' do vcr('entry/raw_with_links') { nyancat = create_client.entry('nyancat') marshal_nyancat = Marshal.load(Marshal.dump(nyancat.raw)) nyancat.raw_with_links expect(marshal_nyancat).to eq(nyancat.raw) } end describe 'can be marshalled' do def test_dump(nyancat) dump = Marshal.dump(nyancat) yield if block_given? new_cat = Marshal.load(dump) # Attributes expect(new_cat).to be_a Contentful::Entry expect(new_cat.name).to eq "Nyan Cat" expect(new_cat.lives).to eq 1337 # Single linked objects expect(new_cat.best_friend).to be_a Contentful::Entry expect(new_cat.best_friend.name).to eq "Happy Cat" # Array of linked objects expect(new_cat.cat_pack.count).to eq 2 expect(new_cat.cat_pack[0].name).to eq "Happy Cat" expect(new_cat.cat_pack[1].name).to eq "Worried Cat" # Nested Links expect(new_cat.best_friend.best_friend).to be_a Contentful::Entry expect(new_cat.best_friend.best_friend.name).to eq "Nyan Cat" # Asset expect(new_cat.image.file.url).to eq "//images.contentful.com/cfexampleapi/4gp6taAwW4CmSgumq2ekUm/9da0cd1936871b8d72343e895a00d611/Nyan_cat_250px_frame.png" end it 'marshals properly when entry_mapping changed' do vcr('entry/marshall') { class TestEntryMapping; end nyancat = create_client(gzip_encoded: false, max_include_resolution_depth: 2, entry_mapping: { 'irrelevant_model' => TestEntryMapping }).entries(include: 2, 'sys.id' => 'nyancat').first test_dump(nyancat) { Object.send(:remove_const, :TestEntryMapping) } } end it 'marshals properly' do vcr('entry/marshall') { nyancat = create_client(gzip_encoded: false, max_include_resolution_depth: 2).entries(include: 2, 'sys.id' => 'nyancat').first test_dump(nyancat) } end it 'marshals with a logger set but keeps the instance' do logger = Logger.new(IO::NULL) vcr('entry/marshall') { nyancat = create_client(gzip_encoded: false, max_include_resolution_depth: 2, logger: logger).entries(include: 2, 'sys.id' => 'nyancat').first expect(nyancat.instance_variable_get(:@configuration)[:logger]).to eq(logger) test_dump(nyancat) expect(nyancat.instance_variable_get(:@configuration)[:logger]).to eq(logger) } end it 'can remarshall an unmarshalled object' do vcr('entry/marshall') { nyancat = create_client(max_include_resolution_depth: 2).entries(include: 2, 'sys.id' => 'nyancat').first # The double load/dump is on purpose test_dump(Marshal.load(Marshal.dump(nyancat))) } end it 'can properly marshal multiple level nested resources - #138' do vcr('entry/marshal_138') { parent = create_client( space: 'j8tb59fszch7', access_token: '5f711401f965951eb724ac72ac905e13d892294ba209268f13a9b32e896c8694', dynamic_entries: :auto, max_include_resolution_depth: 5 ).entry('5aV3O0l5jU0cwQ2OkyYsyU') rehydrated = Marshal.load(Marshal.dump(parent)) expect(rehydrated.childs.first.image1.url).to eq '//images.contentful.com/j8tb59fszch7/7FjliblAmAoGMwU62MeQ6k/62509df90ef4bed38c0701bb9aa8c74c/Funny-Cat-Pictures-with-Captions-25.jpg' expect(rehydrated.childs.first.image2.url).to eq '//images.contentful.com/j8tb59fszch7/1pbGuWZ27O6GMO0OGemgcA/a4185036a3640ad4491f38d8926003ab/Funny-Cat-Pictures-with-Captions-1.jpg' expect(rehydrated.childs.last.image1.url).to eq '//images.contentful.com/j8tb59fszch7/4SXVTr0KEUyWiMMCOaUeUU/c9fa2246d5529a9c8e1ec6f5387dc4f6/e0194eca1c8135636ce0e014341548c3.jpg' expect(rehydrated.childs.last.image2.url).to eq '//images.contentful.com/j8tb59fszch7/1NU1YcNQJGIA22gAKmKqWo/56fa672bb17a7b7ae2773d08e101d059/57ee64921c25faa649fc79288197c313.jpg' } end it 'filters out unpublished resources after rehydration' do vcr('entry/marshal_unpublished') { parent = create_client( space: 'z3eix6mwjid2', access_token: '9047c4394a2130dff8e9dc544a7a3ec299703fdac8e52575eb5a6678be06c468', dynamic_entries: :auto ).entry('5Etc0jWzIWwMeSu4W0SCi8') rehydrated = Marshal.load(Marshal.dump(parent)) expect(rehydrated.children).to be_empty preview_parent = create_client( space: 'z3eix6mwjid2', access_token: '38153b942011a70b5482fda61c6a3a9d22f5e8a512662dac00fcf7eb344b75f4', dynamic_entries: :auto, api_url: 'preview.contentful.com' ).entry('5Etc0jWzIWwMeSu4W0SCi8') preview_rehydrated = Marshal.load(Marshal.dump(preview_parent)) expect(preview_rehydrated.children).not_to be_empty expect(preview_rehydrated.children.first.title).to eq 'Child' } end end describe 'incoming links' do let(:client) { create_client } it 'will fetch entries referencing the entry using a query' do vcr('entry/search_link_to_entry') { entries = client.entries(links_to_entry: 'nyancat') expect(entries).not_to be_empty expect(entries.count).to eq 1 expect(entries.first.id).to eq 'happycat' } end it 'will fetch entries referencing the entry using instance method' do vcr('entry/search_link_to_entry') { entries = entry.incoming_references client expect(entries).not_to be_empty expect(entries.count).to eq 1 expect(entries.first.id).to eq 'happycat' } end it 'will fetch entries referencing the entry using instance method + query' do vcr('entry/search_link_to_entry_with_custom_query') { entries = entry.incoming_references(client, { content_type: 'cat', select: ['fields.name'] }) expect(entries).not_to be_empty expect(entries.count).to eq 1 expect(entries.first.id).to eq 'happycat' expect(entries.first.fields.keys).to eq([:name]) } end end describe 'select operator' do let(:client) { create_client } context 'with sys sent' do it 'properly creates an entry' do vcr('entry/select_only_sys') { entry = client.entries(select: ['sys'], 'sys.id' => 'nyancat').first expect(entry.fields).to be_empty expect(entry.entry?).to be_truthy } end describe 'can contain only one field' do context 'with content_type sent' do it 'will properly create the entry with one field' do vcr('entry/select_one_field_proper') { entry = client.entries(content_type: 'cat', select: ['sys', 'fields.name'], 'sys.id' => 'nyancat').first expect(entry.fields).not_to be_empty expect(entry.entry?).to be_truthy expect(entry.fields[:name]).to eq 'Nyan Cat' expect(entry.fields).to eq({name: 'Nyan Cat'}) } end end context 'without content_type sent' do it 'will raise an error' do vcr('entry/select_one_field') { expect { client.entries(select: ['sys', 'fields.name'], 'sys.id' => 'nyancat') }.to raise_error Contentful::BadRequest } end end end end context 'without sys sent' do it 'will enforce sys anyway' do vcr('entry/select_no_sys') { entry = client.entries(select: ['fields'], 'sys.id' => 'nyancat').first expect(entry.id).to eq 'nyancat' expect(entry.sys).not_to be_empty } end it 'works with empty array as well, as sys is enforced' do vcr('entry/select_empty_array') { entry = client.entries(select: [], 'sys.id' => 'nyancat').first expect(entry.id).to eq 'nyancat' expect(entry.sys).not_to be_empty } end end end describe 'reuse objects' do it 'should handle recursion as well as not reusing' do vcr('entry/include_resolution') { entry = create_client(reuse_objects: true).entry('nyancat', include: 2) expect(entry.best_friend.name).to eq 'Happy Cat' expect(entry .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend.name).to eq 'Nyan Cat' } end it 'should use the same object for the same entry' do vcr('entry/include_resolution') { entry = create_client(reuse_entries: true).entry('nyancat', include: 2) expect(entry.best_friend.name).to eq 'Happy Cat' expect(entry.best_friend.best_friend).to be(entry) } end it 'works on nested structures with unique objects' do vcr('entry/include_resolution_uniques') { entry = create_client( space: 'v7cxgyxt0w5x', access_token: '96e5d256e9a5349ce30e84356597e409f8f1bb485cb4719285b555e0f78aa27e', reuse_entries: true ).entry('1nLXjjWvk4MEeWeQCWmymc', include: 10) expect(entry.title).to eq '1' expect(entry .child.child .child.child .child.child .child.child .child.title).to eq '10' expect(entry .child.child .child.child .child.child .child.child .child.child.title).to eq '1' expect(entry .child.child.child.child .child.child.child.child .child.child.child.child .child.child.child.child .child.child.child.child.title).to eq '1' } end end describe 'include resolution' do it 'should not reuse objects by default' do vcr('entry/include_resolution') { entry = create_client.entry('nyancat', include: 2) expect(entry.best_friend.name).to eq 'Happy Cat' expect(entry.best_friend.best_friend).not_to be(entry) } end it 'defaults to 20 depth' do vcr('entry/include_resolution') { entry = create_client.entry('nyancat', include: 2) expect(entry.best_friend.name).to eq 'Happy Cat' expect(entry .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend.name).to eq 'Nyan Cat' expect(entry .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend.best_friend .best_friend).to be_a ::Contentful::Link } end it 'can be configured arbitrarily' do vcr('entry/include_resolution') { entry = create_client(max_include_resolution_depth: 3).entry('nyancat', include: 2) expect(entry.best_friend.name).to eq 'Happy Cat' expect(entry .best_friend.best_friend .best_friend.name).to eq 'Happy Cat' expect(entry .best_friend.best_friend .best_friend.best_friend).to be_a ::Contentful::Link } end it 'works on nested structures with unique objects' do vcr('entry/include_resolution_uniques') { entry = create_client( space: 'v7cxgyxt0w5x', access_token: '96e5d256e9a5349ce30e84356597e409f8f1bb485cb4719285b555e0f78aa27e', ).entry('1nLXjjWvk4MEeWeQCWmymc', include: 10) expect(entry.title).to eq '1' expect(entry .child.child .child.child .child.child .child.child .child.title).to eq '10' expect(entry .child.child .child.child .child.child .child.child .child.child.title).to eq '1' expect(entry .child.child.child.child .child.child.child.child .child.child.child.child .child.child.child.child .child.child.child.child.title).to eq '1' } end end describe 'issues' do it 'filters out unresolvable assets' do vcr('entries/unresolvable_assets') { client = create_client(space: 'facgnwwgj5fe', access_token: '4d0f55d940975f78139daae5d965b463c0816e88ad16062d2c1ee3d6cb930521') entry = client.entry('gLVzQlb09IeOeU181fwtz') expect(entry.single_asset).to be_nil expect(entry.multi_asset.size).to eq 1 expect(entry.raw["fields"]["multiAsset"].size).to eq 2 } end it 'Symbol/Text field with null values should be serialized as nil - #117' do vcr('entries/issue_117') { client = create_client(space: '8jbbayggj9gj', access_token: '4ce0108f04e55c76476ba84ab0e6149734db73d67cd1b429323ef67f00977e07') entry = client.entries.first expect(entry.nil).to be_nil expect(entry.nil).not_to eq '' } end describe 'JSON Fields should not be treated as locale data - #96' do before do vcr('entry/json_objects_client') { @client = create_client( space: 'h425t6gef30p', access_token: '278f7aa72f2eb90c0e002d60f85bf2144c925acd2d37dd990d3ca274f25076cf', dynamic_entries: :auto ) } vcr('entry/json_objects') { @entry = @client.entries.first } end it 'only has default locale' do expect(@entry.locales).to eq ['en-US'] end it 'can obtain all values properly' do expect(@entry.name).to eq('Test') expect(@entry.object_test).to eq({ null: nil, text: 'some text', array: [1, 2, 3], number: 123, boolean: true, object: { null: nil, text: 'bar', array: [1, 2, 3], number: 123, boolean: false, object: {foo: 'bar'} } }) end end it 'Number (Integer and Decimal) values get properly serialized - #125' do vcr('entries/issue_125') { client = create_client(space: 'zui87wsu8q80', access_token: '64ff902c58cd14ea063d3ded810d1111a0266537e9aba283bad3319b1762c302', dynamic_entries: :auto) entry = client.entries.first expect(entry.integer).to eq 123 expect(entry.decimal).to eq 12.3 } end it 'unresolvable entries get filtered from results' do vcr('entries/unresolvable_filter') { client = create_client(space: '011npgaszg5o', access_token: '42c9d93410a7319e9a735671fc1e415348f65e94a99fc768b70a7c649859d4fd', dynamic_entries: :auto) entry = client.entry('1HR1QvURo4MoSqO0eqmUeO') expect(entry.modules.size).to eq 2 } end it 'unresolvable entries get filtered from results in deeply nested objects - #177' do vcr('entries/unresolvable_filter_deeply_nested') { client = create_client(space: 'z471hdso7l1a', access_token: '8a0e09fe71f1cb41e8788ace86a8c8d9d084599fe43a40070f232045014d2585', dynamic_entries: :auto) entry = client.entry('1hb8sipClkQ8ggeGaeSQWm', include: 3) expect(entry.should_published.first.should_unpublished.size).to eq 0 } end end describe 'camel case' do it 'supports camel case' do vcr('entry') { entry = create_client(use_camel_case: true).entry 'nyancat' expect(entry.bestFriend.name).to eq 'Happy Cat' expect(entry.createdAt).to be_a DateTime } end end describe 'empty fields' do context 'when default configuration' do it 'raises an exception by default' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto ).entry('2t1x77MgUA4SM2gMiaUcsy') expect { entry.title }.to raise_error Contentful::EmptyFieldError } end it 'returns nil if raise_for_empty_fields is false' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto, raise_for_empty_fields: false ).entry('2t1x77MgUA4SM2gMiaUcsy') expect(entry.title).to be_nil } end it 'will properly raise NoMethodError for non-fields' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto ).entry('2t1x77MgUA4SM2gMiaUcsy') expect { entry.unexisting_field }.to raise_error NoMethodError } end end context 'when use_camel_case is true it should still work' do it 'raises an exception by default' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto, use_camel_case: true ).entry('2t1x77MgUA4SM2gMiaUcsy') expect { entry.title }.to raise_error Contentful::EmptyFieldError } end it 'returns nil if raise_for_empty_fields is false' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto, raise_for_empty_fields: false, use_camel_case: true ).entry('2t1x77MgUA4SM2gMiaUcsy') expect(entry.title).to be_nil } end it 'will properly raise NoMethodError for non-fields' do vcr('entries/empty_fields') { entry = create_client( space: 'z4ssexir3p93', access_token: 'e157fdaf7b325b71d07a94b7502807d4cfbbb1a34e69b7856838e25b92777bc6', dynamic_entries: :auto, use_camel_case: true ).entry('2t1x77MgUA4SM2gMiaUcsy') expect { entry.unexisting_field }.to raise_error NoMethodError } end end end describe 'rich text support' do it 'properly serializes and resolves includes' do vcr('entries/rich_text') { entry = create_client( space: 'jd7yc4wnatx3', access_token: '6256b8ef7d66805ca41f2728271daf27e8fa6055873b802a813941a0fe696248', raise_errors: true, dynamic_entries: :auto, gzip_encoded: false ).entry('4BupPSmi4M02m0U48AQCSM') expected_entry_occurrances = 2 embedded_entry_index = 1 entry.body['content'].each do |content| if content['nodeType'] == 'embedded-entry-block' expect(content['data']['target']).to be_a Contentful::Entry expect(content['data']['target'].body).to eq "Embedded #{embedded_entry_index}" expected_entry_occurrances -= 1 embedded_entry_index += 1 end end expect(expected_entry_occurrances).to eq 0 } end it 'doesnt hydrate the same entry twice - #194' do vcr('entries/rich_text_hydration_issue') { entry = nil expect { entry = create_client( space: 'fds721b88p6b', access_token: '45ba81cc69423fcd2e3f0a4779de29481bb5c11495bc7e14649a996cf984e98e', raise_errors: true, dynamic_entries: :auto, gzip_encoded: false ).entry('1tBAu0wP9qAQEg6qCqMics') }.not_to raise_error expect(entry.children[0].id).to eq entry.children[1].id expect(entry.children[0].body).to eq entry.children[1].body } end it 'respects content in data attribute if its not a Link' do vcr('entries/rich_text_nested_fields') { entry = create_client( space: 'jd7yc4wnatx3', access_token: '6256b8ef7d66805ca41f2728271daf27e8fa6055873b802a813941a0fe696248', raise_errors: true, dynamic_entries: :auto, gzip_encoded: false ).entry('6NGLswCREsGA28kGouScyY') expect(entry.body['content'][0]).to eq({ 'data' => {}, 'content' => [ {'marks' => [], 'value' => 'A link to ', 'nodeType' => 'text', 'nodeClass' => 'text'}, { 'data' => {'uri' => 'https://google.com'}, 'content' => [{'marks' => [], 'value' => 'google', 'nodeType' => 'text', 'nodeClass' => 'text'}], 'nodeType' => 'hyperlink', 'nodeClass' => 'inline' }, {'marks' => [], 'value' => '', 'nodeType' => 'text', 'nodeClass' => 'text'} ], 'nodeType' => 'paragraph', 'nodeClass' => 'block' }) } end it 'supports includes in nested fields' do vcr('entries/rich_text_nested_fields') { entry = create_client( space: 'jd7yc4wnatx3', access_token: '6256b8ef7d66805ca41f2728271daf27e8fa6055873b802a813941a0fe696248', raise_errors: true, dynamic_entries: :auto, gzip_encoded: false ).entry('6NGLswCREsGA28kGouScyY') expect(entry.body['content'][3]['nodeType']).to eq('unordered-list') expect(entry.body['content'][3]['content'][2]['content'][0]['data']['target'].is_a?(Contentful::Entry)).to be_truthy expect(entry.body['content'][4]['nodeType']).to eq('ordered-list') expect(entry.body['content'][4]['content'][2]['content'][0]['data']['target'].is_a?(Contentful::Entry)).to be_truthy } end it 'returns a link when resource is valid but unreachable' do vcr('entries/rich_text_unresolved_relationships') { parent = create_client( space: 'jd7yc4wnatx3', access_token: '6256b8ef7d66805ca41f2728271daf27e8fa6055873b802a813941a0fe696248', raise_errors: true, dynamic_entries: :auto, gzip_encoded: false ).entry('4fvSwl5Ob6UEWKg6MQicuC') entry = parent.rich_text_child expect(entry.body['content'][19]['data']['target'].is_a?(Contentful::Link)).to be_truthy } end end describe 'tags metadata' do let(:entry_id) { '52GcYcPOPhuhlaogl05DIh' } it 'can load an entry with tags' do vcr('entry/with_tags') { expect { entry = create_client.entry(entry_id) }.not_to raise_error } end it 'hydrates tags' do vcr('entry/with_tags') { entry = create_client.entry(entry_id) expect(entry._metadata[:tags].first).to be_a Contentful::Link } end it 'loads tag links with their proper attributes' do vcr('entry/with_tags') { entry = create_client.entry(entry_id) tag = entry._metadata[:tags].first expect(tag.id).to eq 'mobQa' expect(tag.link_type).to eq 'Tag' } end end describe 'concepts metadata' do let(:entry_id) { 'tIb8i9uSg9giCeDIWCvi1' } it 'can load an entry with concepts' do vcr('entry/with_concepts') { expect { entry = create_client.entry(entry_id) }.not_to raise_error } end it 'hydrates concepts' do vcr('entry/with_concepts') { entry = create_client.entry(entry_id) expect(entry._metadata[:concepts].first).to be_a Contentful::Link } end it 'loads concept links with their proper attributes' do vcr('entry/with_concepts') { entry = create_client.entry(entry_id) concept = entry._metadata[:concepts].first expect(concept.id).to eq '5iRG7dAusVFUOh9SrexDqQ' expect(concept.link_type).to eq 'TaxonomyConcept' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/space_spec.rb
spec/space_spec.rb
require 'spec_helper' describe Contentful::Space do let(:space) { vcr('space') { create_client.space } } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(space.sys).to be_a Hash expect(space.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(space.id).to eq 'cfexampleapi' end it 'has #type' do expect(space.type).to eq 'Space' end end describe 'Properties' do it 'has #name' do expect(space.name).to eq 'Contentful Example API' end it 'has #locales' do expect(space.locales).to be_a Array expect(space.locales.first).to be_a Contentful::Locale end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/array_spec.rb
spec/array_spec.rb
require 'spec_helper' class CustomClass < Contentful::Entry; end describe Contentful::Array do let(:client) { create_client } let(:array) { vcr('array') { client.content_types } } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(array.sys).to be_a Hash expect(array.sys.keys.sample).to be_a Symbol end it 'has #type' do expect(array.type).to eq 'Array' end end describe 'Properties' do it 'has #total' do expect(array.total).to eq 4 end it 'has #skip' do expect(array.skip).to eq 0 end it 'has #limit' do expect(array.limit).to eq 100 end it 'has #items which contain resources' do expect(array.items).to be_a Array expect(array.items.sample).to be_a Contentful::BaseResource end end describe '#[]' do it 'provides access to items by index' do expect(array[0]).to be_a Contentful::BaseResource end it 'provides access to items by two indices' do expect(array[0, 4]).to eq array.items end end describe '#each' do it 'is an Enumerator' do expect(array.each).to be_a Enumerator end it 'iterates over items' do expect(array.each.to_a).to eq array.items end it 'includes Enumerable' do expect(array.map { |r| r.type }).to eq array.items.map { |r| r.type } end end describe "#to_ary" do it 'is an array' do expect(array.to_ary).to be_a ::Array end it 'returns items' do expect(array.to_ary).to eq array.items end end describe '#next_page' do it 'requests more of the same content from the server, using its limit and skip values' do array_page_1 = vcr('array_page_1') { create_client.content_types(skip: 3, limit: 2) } array_page_2 = vcr('array_page_2') { array_page_1.next_page(client) } expect(array_page_2).to be_a Contentful::Array expect(array_page_2.limit).to eq 2 expect(array_page_2.skip).to eq 5 end it 'will return false if #request not available' do expect(Contentful::Array.new({}).reload).to be_falsey end it 'respects query parameters' do array_page_1 = vcr('query_array_1') { client.entries(content_type: 'cat', limit: 1) } array_page_2 = vcr('query_array_2') { array_page_1.next_page(client) } expect(array_page_1).to be_a Contentful::Array expect(array_page_2).to be_a Contentful::Array expect(array_page_1.query).to include(content_type: 'cat') expect(array_page_2.query).to include(content_type: 'cat') expect(array_page_1.size).to eq 1 expect(array_page_2.size).to eq 1 expect(array_page_1[0].content_type.id).to eq 'cat' expect(array_page_2[0].content_type.id).to eq 'cat' expect(array_page_1[0].id).not_to eq array_page_2[0].id end end describe 'marshalling' do it 'marshals/unmarshals properly - #132' do re_array = Marshal.load(Marshal.dump(array)) expect(re_array.endpoint).to eq array.endpoint expect(re_array.total).to eq array.total expect(re_array.limit).to eq array.limit expect(re_array.skip).to eq array.skip expect(re_array.items).to eq array.items end it 'marshals nested includes propertly - #138' do vcr('array/nested_resources') { client = create_client( space: 'j8tb59fszch7', access_token: '5f711401f965951eb724ac72ac905e13d892294ba209268f13a9b32e896c8694', dynamic_entries: :auto, max_include_resolution_depth: 5 ) entries = client.entries(content_type: 'child') rehydrated = Marshal.load(Marshal.dump(entries)) expect(entries.inspect).to eq rehydrated.inspect expect(entries.first.image1.url).to eq rehydrated.first.image1.url expect(entries.last.image1.url).to eq rehydrated.last.image1.url expect(entries.first.image2.url).to eq rehydrated.first.image2.url expect(entries.last.image2.url).to eq rehydrated.last.image2.url } end it 'marshals custom resources properly - #138' do vcr('array/marshal_custom_classes') { client = create_client( space: 'j8tb59fszch7', access_token: '5f711401f965951eb724ac72ac905e13d892294ba209268f13a9b32e896c8694', dynamic_entries: :auto, max_include_resolution_depth: 5, entry_mapping: { 'parent' => CustomClass } ) entries = client.entries(content_type: 'parent') expect(entries.first.inspect).to eq "<CustomClass[parent] id='5aV3O0l5jU0cwQ2OkyYsyU'>" dehydrated = Marshal.load(Marshal.dump(entries)) expect(dehydrated.first.inspect).to eq "<CustomClass[parent] id='5aV3O0l5jU0cwQ2OkyYsyU'>" } end it 'filters out unpublished resources after rehydration' do vcr('array/marshal_unpublished') { parent = create_client( space: 'z3eix6mwjid2', access_token: '9047c4394a2130dff8e9dc544a7a3ec299703fdac8e52575eb5a6678be06c468', dynamic_entries: :auto ).entries('sys.id': '5Etc0jWzIWwMeSu4W0SCi8') rehydrated = Marshal.load(Marshal.dump(parent)) expect(rehydrated.first.children).to be_empty preview_parent = create_client( space: 'z3eix6mwjid2', access_token: '38153b942011a70b5482fda61c6a3a9d22f5e8a512662dac00fcf7eb344b75f4', dynamic_entries: :auto, api_url: 'preview.contentful.com' ).entries('sys.id': '5Etc0jWzIWwMeSu4W0SCi8') preview_rehydrated = Marshal.load(Marshal.dump(preview_parent)) expect(preview_rehydrated.first.children).not_to be_empty expect(preview_rehydrated.first.children.first.title).to eq 'Child' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/resource_building_spec.rb
spec/resource_building_spec.rb
require 'spec_helper' describe 'Resource Building Examples' do it 'can deal with arrays' do request = Contentful::Request.new(nil, 'entries') response = Contentful::Response.new(raw_fixture('link_array'), request) resource = Contentful::ResourceBuilder.new(response.object).run expect(resource.fields[:links]).to be_a Array expect(resource.fields[:links].first).to be_a Contentful::Link end it 'replaces links with included versions if present' do request = Contentful::Request.new(nil, 'entries') response = Contentful::Response.new(raw_fixture('includes'), request) resource = Contentful::ResourceBuilder.new(response.object).run.first expect(resource.fields[:links]).to be_a Array expect(resource.fields[:links].first).to be_a Contentful::Entry end it 'can also reference itself' do request = Contentful::Request.new(nil, 'entries') response = Contentful::Response.new(raw_fixture('self_link'), request) resource = Contentful::ResourceBuilder.new(response.object).run.first other_resource = resource.fields[:e] expect(other_resource).to be_a Contentful::Entry expect(other_resource.fields[:e]).to eq resource end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/field_spec.rb
spec/field_spec.rb
require 'spec_helper' describe Contentful::Field do let(:field) { vcr('field') { create_client.content_type('cat').fields.first } } let(:linkField) { vcr('linkField') { create_client.content_type('cat').fields.select { |f| f.id == 'image' }.first } } let(:arrayField) { vcr('arrayField') { Contentful::Client.new( space: 'wl1z0pal05vy', access_token: '9b76e1bbc29eb513611a66b9fc5fb7acd8d95e83b0f7d6bacfe7ec926c819806' ).content_type('2PqfXUJwE8qSYKuM0U6w8M').fields.select { |f| f.id == 'categories' }.first } } describe 'Properties' do it 'has #id' do expect(field.id).to eq 'name' end it 'has #name' do expect(field.name).to eq 'Name' end it 'has #type' do expect(field.type).to eq 'Text' end it 'could have #items' do expect(field).to respond_to :items end it 'has #required' do expect(field.required).to be_truthy end it 'has #localized' do expect(field.required).to be_truthy end end describe 'Link field properties' do it 'has #type' do expect(linkField.type).to eq 'Link' end it 'has #linkType' do expect(linkField.link_type).to eq 'Asset' end end describe 'Array field properties' do it 'has #type' do expect(arrayField.type).to eq 'Array' end it 'has #items' do expect(arrayField.items.type).to eq 'Link' expect(arrayField.items.link_type).to eq 'Entry' end end describe 'issues' do describe 'json field' do it 'can coerce properly when top level is not object' do coercion = Contentful::ObjectCoercion.new([{foo: 123}]) expect(coercion.coerce).to eq [{foo: 123}] coercion = Contentful::ObjectCoercion.new('foobar') expect(coercion.coerce).to eq 'foobar' coercion = Contentful::ObjectCoercion.new(true) expect(coercion.coerce).to eq true coercion = Contentful::ObjectCoercion.new(123) expect(coercion.coerce).to eq 123 coercion = Contentful::ObjectCoercion.new({foo: 123}) expect(coercion.coerce).to eq(foo: 123) end end describe 'datetime field' do it 'can coerce properly when value is nil' do coercion = Contentful::DateCoercion.new(nil) expect(coercion.coerce).to eq(nil) end it 'can coerce properly when value is already datetime' do value = DateTime.new coercion = Contentful::DateCoercion.new(value) expect(coercion.coerce).to eq value end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/taxonomy_concept_spec.rb
spec/taxonomy_concept_spec.rb
require 'spec_helper' describe Contentful::TaxonomyConcept do let(:client) { create_client } let(:taxonomy_concept) { vcr('taxonomy_concept') { client.taxonomy_concept('5iRG7dAusVFUOh9SrexDqQ') } } describe 'Client method' do it 'can be retrieved via client.taxonomy_concept' do expect(taxonomy_concept).to be_a Contentful::TaxonomyConcept expect(taxonomy_concept.sys[:id]).to eq '5iRG7dAusVFUOh9SrexDqQ' end end describe 'System Properties' do it 'has a sys property' do expect(taxonomy_concept.sys).to be_a Hash end it 'has the correct sys properties' do expect(taxonomy_concept.sys[:id]).to eq '5iRG7dAusVFUOh9SrexDqQ' expect(taxonomy_concept.sys[:type]).to eq 'TaxonomyConcept' expect(taxonomy_concept.sys[:created_at]).to be_a DateTime expect(taxonomy_concept.sys[:updated_at]).to be_a DateTime expect(taxonomy_concept.sys[:version]).to eq 2 end end describe 'Basic Properties' do it 'has a uri property' do expect(taxonomy_concept.uri).to eq 'https://example/testconcept' end it 'has notations' do expect(taxonomy_concept.notations).to eq ['SLR001'] end end describe 'Localized Fields' do it 'has pref_label' do expect(taxonomy_concept.pref_label).to eq 'TestConcept' end it 'has alt_labels' do expect(taxonomy_concept.alt_labels).to eq ['Couches'] end it 'has hidden_labels' do expect(taxonomy_concept.hidden_labels).to eq ['Sopha'] end it 'has note' do expect(taxonomy_concept.note).to eq 'Excepteur sint occaecat cupidatat non proident' end it 'has change_note' do expect(taxonomy_concept.change_note).to be_nil end it 'has definition' do expect(taxonomy_concept.definition).to be_nil end it 'has editorial_note' do expect(taxonomy_concept.editorial_note).to eq 'labore et dolore magna aliqua' end it 'has example' do expect(taxonomy_concept.example).to eq 'Lorem ipsum dolor sit amet' end it 'has history_note' do expect(taxonomy_concept.history_note).to eq 'sed do eiusmod tempor incididunt' end it 'has scope_note' do expect(taxonomy_concept.scope_note).to eq 'consectetur adipiscing elit' end it 'supports locale-specific access' do expect(taxonomy_concept.pref_label('en-US')).to eq 'TestConcept' expect(taxonomy_concept.pref_label('de-DE')).to be_nil end end describe 'Relationships' do it 'has broader concepts' do expect(taxonomy_concept.broader).to be_an Array expect(taxonomy_concept.broader).to be_empty end it 'has related concepts' do expect(taxonomy_concept.related).to be_an Array expect(taxonomy_concept.related).to be_empty end it 'has concept schemes' do expect(taxonomy_concept.concept_schemes).to be_an Array expect(taxonomy_concept.concept_schemes.first['sys']['type']).to eq 'Link' expect(taxonomy_concept.concept_schemes.first['sys']['linkType']).to eq 'TaxonomyConceptScheme' expect(taxonomy_concept.concept_schemes.first['sys']['id']).to eq '4EQT881T6sG9XpzNwb9y9R' end end describe 'Type checking' do it 'is a taxonomy concept' do expect(taxonomy_concept.taxonomy_concept?).to be true end it 'is not an entry' do expect(taxonomy_concept.entry?).to be false end it 'is not an asset' do expect(taxonomy_concept.asset?).to be false end end describe 'Serialization' do it 'can be marshaled and unmarshaled' do marshaled = Marshal.dump(taxonomy_concept) unmarshaled = Marshal.load(marshaled) expect(unmarshaled.sys[:id]).to eq taxonomy_concept.sys[:id] expect(unmarshaled.pref_label).to eq taxonomy_concept.pref_label expect(unmarshaled.taxonomy_concept?).to be true end end describe 'raw mode' do let(:raw_client) { create_client(raw_mode: true) } it 'returns raw response when raw_mode is enabled' do vcr('taxonomy_concept_raw') do result = raw_client.taxonomy_concept('5iRG7dAusVFUOh9SrexDqQ') expect(result).to be_a Contentful::Response expect(result.object['sys']['id']).to eq '5iRG7dAusVFUOh9SrexDqQ' expect(result.object['sys']['type']).to eq 'TaxonomyConcept' end end it 'should return JSON with correct structure' do expected = { "sys" => { "id" => "5iRG7dAusVFUOh9SrexDqQ", "type" => "TaxonomyConcept", "createdAt" => "2025-03-21T05:54:15.434Z", "updatedAt" => "2025-06-23T06:05:25.107Z", "version" => 4 }, "uri" => "https://example/testconcept", "notations" => ["SLR001"], "conceptSchemes" => [ { "sys" => { "id" => "4EQT881T6sG9XpzNwb9y9R", "type" => "Link", "linkType" => "TaxonomyConceptScheme" } } ], "broader" => [], "related" => [], "prefLabel" => { "en-US" => "TestConcept" }, "altLabels" => { "en-US" => ["Couches"] }, "hiddenLabels" => { "en-US" => ["Sopha"] }, "note" => { "en-US" => "Excepteur sint occaecat cupidatat non proident" }, "changeNote" => nil, "definition" => nil, "editorialNote" => {"en-US" => ""}, "example" => { "en-US" => "Lorem ipsum dolor sit amet" }, "historyNote" => {"en-US" => ""}, "scopeNote" => { "en-US" => "consectetur adipiscing elit" } } vcr('taxonomy_concept_raw') do result = raw_client.taxonomy_concept('5iRG7dAusVFUOh9SrexDqQ') expect(result.object).to eql expected end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/locale_spec.rb
spec/locale_spec.rb
require 'spec_helper' describe Contentful::Locale do let(:locale) { vcr('locale') { create_client.space.locales.first } } describe 'Properties' do it 'has #code' do expect(locale.code).to eq 'en-US' end it 'has #name' do expect(locale.name).to eq 'English' end it 'has #default' do expect(locale.default).to eq true end end describe 'locales endpoint' do it 'locales can be fetched from environments' do vcr('locale_from_environment') { client = create_client( space: 'facgnwwgj5fe', access_token: '<ACCESS_TOKEN>', environment: 'testing' ) locales = client.locales expect(locales).to be_a ::Contentful::Array expect(locales.first).to be_a ::Contentful::Locale expect(locales.first.code).to eq 'en-US' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/sync_page_spec.rb
spec/sync_page_spec.rb
require 'spec_helper' describe Contentful::SyncPage do let(:page_with_more) { vcr('sync_page') { create_client.sync(initial: true).first_page } } let(:page) { vcr('sync_page_2') { create_client.sync.get('https://cdn.contentful.com/spaces/cfexampleapi/environments/master/sync?sync_token=w5ZGw6JFwqZmVcKsE8Kow4grw45QdybCr8Okw6AYwqbDksO3ehvDpUPCgcKsKXbCiAwPC8K2w4LDvsOkw6nCjhPDpcOQADElWsOoU8KGR3HCtsOAwqd6wp_Dulp8w6LDsF_CtsK7Kk05wrMvwrLClMOgG2_Dn2sGPg') } } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(page.sys).to be_a Hash expect(page.sys.keys.sample).to be_a Symbol end it 'has #type' do expect(page.type).to eq 'Array' end end describe 'Properties' do it 'has #items which contain resources' do expect(page_with_more.items).to be_a Array expect(page_with_more.items.sample).to be_a Contentful::BaseResource end end describe 'Fields' do it 'properly deals with nested locale fields' do expect(page_with_more.items.first.fields[:name]).to eq 'London' end end describe '#each' do it 'is an Enumerator' do expect(page.each).to be_a Enumerator end it 'iterates over items' do expect(page.each.to_a).to eq page.items end it 'includes Enumerable' do expect(page.map { |r| r.type }).to eq page.items.map { |r| r.type } end end describe '#next_sync_url' do it 'will return the next_sync_url if there is one' do expect(page.next_sync_url).to be_a String end it 'will return nil if note last page, yet' do expect(page_with_more.next_sync_url).to be_nil end end describe '#next_page_url' do it 'will return the next_page_url if there is one' do expect(page_with_more.next_page_url).to be_a String end it 'will return nil if on last page' do expect(page.next_page_url).to be_nil end end describe '#next_page' do it 'requests the next page' do next_page = vcr('sync_page_2')do page_with_more.next_page end expect(next_page).to be_a Contentful::SyncPage end it 'will return nil if last page' do expect(page.next_page_url).to be_nil end end describe '#next_page?' do it 'will return true if there is a next page' do expect(page_with_more.next_page?).to be_truthy end it 'will return false if last page' do expect(page.next_page?).to be_falsey end end describe '#last_page?' do it 'will return true if no more pages available' do expect(page.last_page?).to be_truthy end it 'will return false if more pages available' do expect(page_with_more.last_page?).to be_falsey end end describe '#sync' do it 'returns the sync that created the page' do expect(page.sync).to be_a Contentful::Sync end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/error_requests_spec.rb
spec/error_requests_spec.rb
require 'spec_helper' class NonCachingClient < Contentful::Client def request_headers headers = super headers['Cf-No-Cache'] = 'foobar' headers end end class RetryLoggerMock < Logger attr_reader :retry_attempts def initialize(*) super @retry_attempts = 0 end def info(message) super @retry_attempts += 1 if message.include?('Contentful API Rate Limit Hit! Retrying') end end describe 'Error Requests' do it 'will return 404 (Unauthorized) if resource not found' do expect_vcr('not found')do create_client.content_type 'not found' end.to raise_error(Contentful::NotFound) end it 'will return 400 (BadRequest) if invalid parameters have been passed' do expect_vcr('bad request')do create_client.entries(some: 'parameter') end.to raise_error(Contentful::BadRequest) end it 'will return 403 (AccessDenied) if ...' do skip end it 'will return 401 (Unauthorized) if wrong credentials are given' do client = Contentful::Client.new(space: 'wrong', access_token: 'credentials') expect_vcr('unauthorized'){ client.entry('nyancat') }.to raise_error(Contentful::Unauthorized) end it 'will return 500 (ServerError) if ...' do skip end it 'will return a 429 if the ratelimit is reached and is not set to retry' do client = Contentful::Client.new(space: 'wrong', access_token: 'credentials', max_rate_limit_retries: 0) expect_vcr('ratelimit') { client.entry('nyancat') }.to raise_error(Contentful::RateLimitExceeded) end it 'will retry on 429 by default' do logger = RetryLoggerMock.new(STDOUT) client = NonCachingClient.new( api_url: 'cdnorigin.flinkly.com', space: '164vhtp008kz', access_token: '7699b6c6f6cee9b6abaa216c71fbcb3eee56cb6f082f57b5e21b2b50f86bdea0', raise_errors: true, logger: logger ) vcr('ratelimit_retry') { 3.times { client.assets } } expect(logger.retry_attempts).to eq 1 end it 'will return 503 (ServiceUnavailable) when the service is unavailable' do client = Contentful::Client.new(space: 'wrong', access_token: 'credentials') expect_vcr('unavailable'){ client.entry('nyancat') }.to raise_error(Contentful::ServiceUnavailable) end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/deleted_entry_spec.rb
spec/deleted_entry_spec.rb
require 'spec_helper' describe 'DeletedEntry' do let(:deleted_entry)do vcr('sync_deleted_entry')do create_client.sync(initial: true, type: 'DeletedEntry').first_page.items[0] end end describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(deleted_entry.sys).to be_a Hash expect(deleted_entry.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(deleted_entry.id).to eq 'CVebBDcQsSsu6yKKIayy' end it 'has #type' do expect(deleted_entry.type).to eq 'DeletedEntry' end it 'has #deleted_at' do expect(deleted_entry.created_at).to be_a DateTime end end describe 'camel case' do it 'supports camel case' do vcr('sync_deleted_entry') { deleted_entry = create_client(use_camel_case: true).sync(initial: true, type: 'DeletedEntry').first_page.items[0] expect(deleted_entry.createdAt).to be_a DateTime } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/includes_spec.rb
spec/includes_spec.rb
require 'spec_helper' describe Contentful::Includes do let(:example_json) { json_fixture('includes') } # This is the expected transformation of the JSON above let(:example_array) { [{"sys"=>{"space"=>{"sys"=>{"type"=>"Link", "linkType"=>"Space", "id"=>"6yahkaf5ehkk"}}, "type"=>"Entry", "contentType"=>{"sys"=>{"type"=>"Link", "linkType"=>"ContentType", "id"=>"tSFLnCNqvuyoMA6SKkQ2W"}}, "id"=>"2fCmT4nxtO6eI6usgoEkQG", "revision"=>1, "createdAt"=>"2014-04-11T10:59:40.249Z", "updatedAt"=>"2014-04-11T10:59:40.249Z", "locale"=>"en-US"}, "fields"=>{"foo"=>"dog", "links"=>[{"sys"=>{"type"=>"Link", "linkType"=>"Entry", "id"=>"5ulKc1zdg4ES0oAKuCe8yA"}}, {"sys"=>{"type"=>"Link", "linkType"=>"Entry", "id"=>"49fzjGhfBCAu6iOqIeg8yQ"}}]}}, {"sys"=>{"space"=>{"sys"=>{"type"=>"Link", "linkType"=>"Space", "id"=>"6yahkaf5ehkk"}}, "type"=>"Entry", "contentType"=>{"sys"=>{"type"=>"Link", "linkType"=>"ContentType", "id"=>"tSFLnCNqvuyoMA6SKkQ2W"}}, "id"=>"49fzjGhfBCAu6iOqIeg8yQ", "revision"=>1, "createdAt"=>"2014-04-11T10:58:58.286Z", "updatedAt"=>"2014-04-11T10:58:58.286Z", "locale"=>"en-US"}, "fields"=>{"foo"=>"nyancat"}}, {"sys"=>{"space"=>{"sys"=>{"type"=>"Link", "linkType"=>"Space", "id"=>"6yahkaf5ehkk"}}, "type"=>"Entry", "contentType"=>{"sys"=>{"type"=>"Link", "linkType"=>"ContentType", "id"=>"tSFLnCNqvuyoMA6SKkQ2W"}}, "id"=>"5ulKc1zdg4ES0oAKuCe8yA", "revision"=>1, "createdAt"=>"2014-04-11T10:59:17.658Z", "updatedAt"=>"2014-04-11T10:59:17.658Z", "locale"=>"en-US"}, "fields"=>{"foo"=>"happycat"}}] } # Another array to test adding two includes together let(:example_array_2) { [{"sys"=>{"space"=>{"sys"=>{"type"=>"Link", "linkType"=>"Space", "id"=>"6yahkaf5ehkk"}}, "type"=>"Entry", "contentType"=>{"sys"=>{"type"=>"Link", "linkType"=>"ContentType", "id"=>"tSFLnCNqvuyoMA6SKkQ2W"}}, "id"=>"1mhHLEpJSZxJR6erF2YWmD", "revision"=>1, "createdAt"=>"2014-04-11T10:58:58.286Z", "updatedAt"=>"2014-04-11T10:58:58.286Z", "locale"=>"en-US"}, "fields"=>{"foo"=>"cheezburger"}}] } subject { described_class.from_response(example_json) } describe '.new' do context 'with no args' do subject { described_class.new } it { is_expected.to be_a Contentful::Includes } it 'has empty items and lookup' do expect(subject.items).to eq([]) expect(subject.lookup).to eq({}) end it 'behaves like an array' do expect(subject.length).to eq(0) expect(subject.to_a).to eq([]) end end context 'with array of includes' do subject { described_class.new(example_array) } it { is_expected.to be_a Contentful::Includes } it 'populates items and lookup' do expect(subject.items).to eq(example_array) expect(subject.lookup.length).to eq(3) end it 'behaves like an array' do expect(subject.length).to eq(3) expect(subject.to_a).to eq(example_array) expect(subject[2]['sys']['id']).to eq('5ulKc1zdg4ES0oAKuCe8yA') end end end describe '.from_response' do subject { described_class.from_response(example_json) } it 'finds the includes in the response and converts them' do expect(subject.items).to eq(example_array) end it 'populates the lookup' do expect(subject.lookup.length).to eq(3) end end describe '#find_link' do let(:link) { {"sys" => {"id" => "49fzjGhfBCAu6iOqIeg8yQ", "linkType" => "Entry"}} } it 'looks up the linked entry' do expect(subject.find_link(link)).to eq(example_array[1]) end end describe '#+' do let(:other) { described_class.new(example_array_2) } it 'adds the arrays and lookups together' do sum = subject + other expect(sum.object_id).not_to eq(subject.object_id) expect(sum.length).to eq(4) expect(sum.lookup).to have_key("Entry:2fCmT4nxtO6eI6usgoEkQG") expect(sum.lookup).to have_key("Entry:49fzjGhfBCAu6iOqIeg8yQ") end context 'other is the same as subject' do let(:other) { described_class.from_response(example_json) } it 'just returns the subject unchanged' do sum = subject + other expect(sum.object_id).to eq(subject.object_id) end end context 'other is the exact same object as subject' do let(:other) { subject } it 'just returns the subject unchanged' do sum = subject + other expect(sum.object_id).to eq(subject.object_id) end end end describe '#dup' do let(:other) { described_class.new(example_array_2) } it 'duplicates the array but also the lookup' do orig = subject # assign subject to a variable so we can call += on it copy = orig.dup orig += other expect(orig.length).to eq(4) expect(copy.length).to eq(3) expect(orig.lookup.length).to eq(4) expect(copy.lookup.length).to eq(3) end end describe 'marshalling' do it 'marshals and unmarshals correctly' do data = Marshal.dump(subject) obj = Marshal.load(data) expect(obj).to be_a Contentful::Includes expect(obj.length).to eq(3) expect(obj.lookup.length).to eq(3) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/location_spec.rb
spec/location_spec.rb
require 'spec_helper' describe Contentful::Location do let(:location)do vcr('location')do Contentful::Client.new( space: 'lzjz8hygvfgu', access_token: '0c6ef483524b5e46b3bafda1bf355f38f5f40b4830f7599f790a410860c7c271', dynamic_entries: :auto, ).entry('3f6fq5ylFCi4kIYAQKsAYG').location end end describe 'Properties' do it 'has #lat' do expect(location.lat).to be_a Float expect(location.lat.to_i).to eq 36 end it 'has #lon' do expect(location.lon).to be_a Float expect(location.lon.to_i).to eq(-94) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/link_spec.rb
spec/link_spec.rb
require 'spec_helper' describe Contentful::Link do let(:client) { create_client } let(:entry) { vcr('entry') { create_client.entry('nyancat') } } let(:link) { entry.space } let(:content_type_link) { entry.content_type } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(link.sys).to be_a Hash expect(link.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(link.id).to eq 'cfexampleapi' end it 'has #type' do expect(link.type).to eq 'Link' end it 'has #link_type' do expect(link.link_type).to eq 'Space' end end describe '#resolve' do it 'queries the api for the resource' do vcr('space')do expect(link.resolve(client)).to be_a Contentful::Space end end it 'queries the api for the resource (different link object)' do vcr('content_type')do expect(content_type_link.resolve(client)).to be_a Contentful::ContentType end end end describe 'camel case' do it 'supports camel case' do vcr('entry') { space_link = create_client(use_camel_case: true).entry('nyancat').space expect(space_link.linkType).to eq 'Space' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/auto_includes_spec.rb
spec/auto_includes_spec.rb
require 'spec_helper' describe 'Auto-include resources' do let(:entries) { vcr('entries') { create_client.entries } } # entries come with asset includes it 'replaces Contentful::Links which are actually included with the resource' do asset = entries.items[1].fields[:image] expect(asset).not_to be_a Contentful::Link expect(asset).to be_a Contentful::Asset end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/client_configuration_spec.rb
spec/client_configuration_spec.rb
require 'spec_helper' describe 'Client Configuration Options' do describe ':space' do it 'is required' do expect do Contentful::Client.new(access_token: 'b4c0n73n7fu1') end.to raise_error(ArgumentError) end end describe ':access_token' do it 'is required' do expect do Contentful::Client.new(space: 'cfexampleapi') end.to raise_error(ArgumentError) end end describe ':secure' do it 'will use https [default]' do expect( create_client.base_url ).to start_with 'https://' end it 'will use http when secure set to false' do expect( create_client(secure: false).base_url ).to start_with 'http://' end end describe ':raise_errors' do it 'will raise response errors if set to true [default]' do expect_vcr('not found')do create_client.content_type 'not found' end.to raise_error Contentful::NotFound end it 'will not raise response errors if set to false' do res = nil expect_vcr('not found')do res = create_client(raise_errors: false).content_type 'not found' end.not_to raise_error expect(res).to be_instance_of Contentful::NotFound end end describe ':log_level' do let(:logger) { Logger.new(STDOUT) } it 'changes the level of the logger instance when given' do expect do create_client(logger: logger, log_level: ::Logger::WARN) end.to change { logger.level }.from(::Logger::DEBUG).to(::Logger::WARN) end it 'does not change the level of the logger instance when not given' do expect do create_client(logger: logger) end.not_to change { logger.level } end end describe ':dynamic_entries' do before :each do Contentful::ContentTypeCache.clear! end it 'will create dynamic entries if dynamic_entry_cache is not empty' do client = create_client(dynamic_entries: :manual) vcr('entry_cache') { client.update_dynamic_entry_cache! } entry = vcr('nyancat') { client.entry('nyancat') } expect(entry).to be_a Contentful::Entry end context ':auto' do it 'will call update dynamic_entry_cache on start-up' do vcr('entry_cache') do create_client(dynamic_entries: :auto) end expect(Contentful::ContentTypeCache.cache).not_to be_empty end end context ':manual' do it 'will not call #update_dynamic_entry_cache! on start-up' do create_client(dynamic_entries: :manual) expect(Contentful::ContentTypeCache.cache).to be_empty end end describe '#update_dynamic_entry_cache!' do let(:client) { create_client(dynamic_entries: :manual) } it 'will fetch all content_types' do expect(client).to receive(:content_types).with(limit: 1000) { {} } client.update_dynamic_entry_cache! end it 'will save dynamic entries in @dynamic_entry_cache' do vcr('entry_cache')do client.update_dynamic_entry_cache! end expect(Contentful::ContentTypeCache.cache).not_to be_empty end end describe '#register_dynamic_entry' do let(:client) { create_client(dynamic_entries: :manual) } it 'can be used to register a dynamic entry manually' do cat = vcr('content_type') { client.content_type 'cat' } client.register_dynamic_entry 'cat', cat expect(Contentful::ContentTypeCache.cache).not_to be_empty end end end describe ':api_url' do it 'is "cdn.contentful.com" [default]' do expect( create_client.configuration[:api_url] ).to eq 'cdn.contentful.com' end it 'will be used as base url' do expect( create_client(api_url: 'cdn2.contentful.com').base_url ).to start_with 'https://cdn2.contentful.com' end end describe ':api_version' do it 'is 1 [default]' do expect( create_client.configuration[:api_version] ).to eq 1 end it 'will used for the http content type request header' do expect( create_client(api_version: 2).request_headers['Content-Type'] ).to eq 'application/vnd.contentful.delivery.v2+json' end end describe ':authentication_mechanism' do describe ':header [default]' do it 'will add the :access_token as authorization bearer token request header' do expect( create_client.request_headers['Authorization'] ).to eq 'Bearer b4c0n73n7fu1' end it 'will not add :access_token to query' do expect( create_client.request_query({})['access_token'] ).to be_nil end end describe ':query_string' do it 'will add the :access_token to query' do expect( create_client(authentication_mechanism: :query_string). request_query({})['access_token'] ).to eq 'b4c0n73n7fu1' end it 'will not add the :access_token as authorization bearer token request header' do expect( create_client(authentication_mechanism: :query_string). request_headers['Authorization'] ).to be_nil end end end describe ':resource_mapping' do it 'lets you register your own resource classes for certain response types' do class MyBetterAsset < Contentful::Asset def https_image_url image_url.sub %r{\A//}, 'https://' end end client = create_client( resource_mapping: { 'Asset' => MyBetterAsset, } ) nyancat = vcr('asset') { client.asset 'nyancat' } expect(nyancat).to be_a MyBetterAsset expect(nyancat.https_image_url).to start_with 'https' end end describe ':entry_mapping' do it 'lets you register your own entry classes for certain entry types' do class Cat < Contentful::Entry end client = create_client( entry_mapping: { 'cat' => Cat } ) nyancat = vcr('entry') { client.entry 'nyancat' } finn = vcr('human') { client.entry 'finn' } expect(nyancat).to be_a Cat expect(finn).to be_a Contentful::Entry end end describe 'X-Contentful-User-Agent headers' do it 'default values' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", ] client = create_client expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['integration', 'app'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'with integration name only' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", "integration foobar;" ] client = create_client(integration_name: 'foobar') expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['app'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'with integration' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", "integration foobar/0.1.0;" ] client = create_client(integration_name: 'foobar', integration_version: '0.1.0') expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['app'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'with application name only' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", "app fooapp;" ] client = create_client(application_name: 'fooapp') expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['integration'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'with application' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", "app fooapp/1.0.0;" ] client = create_client(application_name: 'fooapp', application_version: '1.0.0') expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['integration'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'with all' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};", "integration foobar/0.1.0;", "app fooapp/1.0.0;" ] client = create_client( integration_name: 'foobar', integration_version: '0.1.0', application_name: 'fooapp', application_version: '1.0.0' ) expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) end it 'when only version numbers, skips header' do expected = [ "sdk contentful.rb/#{Contentful::VERSION};", "platform ruby/#{RUBY_VERSION};" ] client = create_client( integration_version: '0.1.0', application_version: '1.0.0' ) expected.each do |h| expect(client.contentful_user_agent).to include(h) end expect(client.contentful_user_agent).to match(/os (Windows|macOS|Linux)(\/.*)?;/i) ['integration', 'app'].each do |h| expect(client.contentful_user_agent).not_to include(h) end end it 'headers include X-Contentful-User-Agent' do client = create_client expect(client.request_headers['X-Contentful-User-Agent']).to eq client.contentful_user_agent end end describe 'timeout options' do let(:full_options) { { timeout_connect: 1, timeout_read: 2, timeout_write: 3 } } it 'allows the three options to be present together' do expect do create_client(full_options) end.not_to raise_error end it 'allows the three options to be omitted' do expect do create_client() end.not_to raise_error end it 'does not allow only some options to be set' do # Test that any combination of 1 or 2 keys is rejected 1.upto(2) do |options_count| full_options.keys.combination(options_count).each do |option_keys| expect do create_client(full_options.select { |key, _| option_keys.include?(key) }) end.to raise_error(ArgumentError) end end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/taxonomy_concept_scheme_spec.rb
spec/taxonomy_concept_scheme_spec.rb
require 'spec_helper' describe Contentful::TaxonomyConceptScheme do let(:client) { create_client } let(:taxonomy_concept_scheme) { vcr('taxonomy_concept_scheme') { client.taxonomy_concept_scheme('4EQT881T6sG9XpzNwb9y9R') } } describe 'Client method' do it 'can be retrieved via client.taxonomy_concept_scheme' do expect(taxonomy_concept_scheme).to be_a Contentful::TaxonomyConceptScheme expect(taxonomy_concept_scheme.sys[:id]).to eq '4EQT881T6sG9XpzNwb9y9R' end end describe 'System Properties' do it 'has a sys property' do expect(taxonomy_concept_scheme.sys).to be_a Hash end it 'has the correct sys properties' do expect(taxonomy_concept_scheme.sys[:id]).to eq '4EQT881T6sG9XpzNwb9y9R' expect(taxonomy_concept_scheme.sys[:type]).to eq 'TaxonomyConceptScheme' expect(taxonomy_concept_scheme.sys[:created_at]).to be_a DateTime expect(taxonomy_concept_scheme.sys[:updated_at]).to be_a DateTime expect(taxonomy_concept_scheme.sys[:version]).to eq 2 end end describe 'Basic Properties' do it 'has a uri property' do expect(taxonomy_concept_scheme.uri).to eq 'https://example.com/testscheme' end it 'has top concepts' do expect(taxonomy_concept_scheme.top_concepts).to be_an Array expect(taxonomy_concept_scheme.top_concepts.first['sys']['type']).to eq 'Link' expect(taxonomy_concept_scheme.top_concepts.first['sys']['linkType']).to eq 'TaxonomyConcept' expect(taxonomy_concept_scheme.top_concepts.first['sys']['id']).to eq '5iRG7dAusVFUOh9SrexDqQ' end it 'has concepts' do expect(taxonomy_concept_scheme.concepts).to be_an Array expect(taxonomy_concept_scheme.concepts.first['sys']['type']).to eq 'Link' expect(taxonomy_concept_scheme.concepts.first['sys']['linkType']).to eq 'TaxonomyConcept' expect(taxonomy_concept_scheme.concepts.first['sys']['id']).to eq '5iRG7dAusVFUOh9SrexDqQ' end it 'has total concepts' do expect(taxonomy_concept_scheme.total_concepts).to eq 1 end end describe 'Localized Fields' do it 'has pref_label' do expect(taxonomy_concept_scheme.pref_label).to eq 'TestScheme' end it 'has definition' do expect(taxonomy_concept_scheme.definition).to eq '' end it 'supports locale-specific access' do expect(taxonomy_concept_scheme.pref_label('en-US')).to eq 'TestScheme' expect(taxonomy_concept_scheme.pref_label('de-DE')).to be_nil end end describe 'Type checking' do it 'is a taxonomy concept scheme' do expect(taxonomy_concept_scheme.taxonomy_concept_scheme?).to be true end it 'is not a taxonomy concept' do expect(taxonomy_concept_scheme.taxonomy_concept?).to be false end it 'is not an entry' do expect(taxonomy_concept_scheme.entry?).to be false end it 'is not an asset' do expect(taxonomy_concept_scheme.asset?).to be false end end describe 'Serialization' do it 'can be marshaled and unmarshaled' do marshaled = Marshal.dump(taxonomy_concept_scheme) unmarshaled = Marshal.load(marshaled) expect(unmarshaled.sys[:id]).to eq taxonomy_concept_scheme.sys[:id] expect(unmarshaled.pref_label).to eq taxonomy_concept_scheme.pref_label expect(unmarshaled.taxonomy_concept_scheme?).to be true end end describe 'raw mode' do let(:raw_client) { create_client(raw_mode: true) } it 'returns raw response when raw_mode is enabled' do vcr('taxonomy_concept_scheme_raw') do result = raw_client.taxonomy_concept_scheme('4EQT881T6sG9XpzNwb9y9R') expect(result).to be_a Contentful::Response expect(result.object['sys']['id']).to eq '4EQT881T6sG9XpzNwb9y9R' expect(result.object['sys']['type']).to eq 'TaxonomyConceptScheme' end end it 'should return JSON with correct structure' do expected = { "sys" => { "id" => "4EQT881T6sG9XpzNwb9y9R", "type" => "TaxonomyConceptScheme", "createdAt" => "2025-03-21T05:53:46.063Z", "updatedAt" => "2025-03-21T05:55:26.969Z", "version" => 2 }, "uri" => "https://example.com/testscheme", "prefLabel" => { "en-US" => "TestScheme" }, "definition" => { "en-US" => "" }, "topConcepts" => [ { "sys" => { "id" => "5iRG7dAusVFUOh9SrexDqQ", "type" => "Link", "linkType" => "TaxonomyConcept" } } ], "concepts" => [ { "sys" => { "id" => "5iRG7dAusVFUOh9SrexDqQ", "type" => "Link", "linkType" => "TaxonomyConcept" } } ], "totalConcepts" => 1 } vcr('taxonomy_concept_scheme_raw') do result = raw_client.taxonomy_concept_scheme('4EQT881T6sG9XpzNwb9y9R') expect(result.object).to eql expected end end end describe 'Collection endpoint' do let(:client) { create_client } it 'can fetch all taxonomy concept schemes' do vcr('taxonomy_concept_schemes') do schemes = client.taxonomy_concept_schemes(limit: 1) expect(schemes).to be_a Contentful::Array expect(schemes.first).to be_a Contentful::TaxonomyConceptScheme expect(schemes.first.sys[:type]).to eq 'TaxonomyConceptScheme' end end it 'supports pagination and query params' do vcr('taxonomy_concept_schemes_pagination') do schemes = client.taxonomy_concept_schemes(limit: 1, order: 'sys.createdAt') expect(schemes.limit).to eq 1 expect(schemes.items.size).to eq 1 expect(schemes.first).to be_a Contentful::TaxonomyConceptScheme expect(schemes.first.pref_label).not_to be_nil expect(schemes.first.sys[:type]).to eq 'TaxonomyConceptScheme' expect(schemes.raw['pages']).to be_a(Hash).or be_nil end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/sync_spec.rb
spec/sync_spec.rb
require 'spec_helper' describe Contentful::Sync do before :each do Contentful::ContentTypeCache.clear! end let(:first_page) do vcr('sync_page')do create_client.sync(initial: true).first_page end end let(:last_page) do vcr('sync_page')do vcr('sync_page_2')do create_client.sync(initial: true).first_page.next_page end end end describe 'environments' do it 'works for environments' do vcr('sync_environment') { page = nil expect { page = create_client( space: 'a22o2qgm356c', access_token: 'bfbc63cf745a037125dbcc64f716a9a0e9d091df1a79e84920b890f87a6e7ab9', environment: 'staging' ).sync(initial: true).first_page }.not_to raise_exception expect(page.items.first).to be_a ::Contentful::Entry expect(page.items.first.environment.id).to eq 'staging' } end end describe '#initialize' do it 'takes an options hash on initialization' do expect do vcr('sync_deletion') { create_client.sync(initial: true, type: 'Deletion').first_page } end.not_to raise_exception end it 'takes a next_sync_url on initialization' do expect do vcr('sync_page_2') { create_client.sync('https://cdn.contentful.com/spaces/cfexampleapi/environments/master/sync?sync_token=w5ZGw6JFwqZmVcKsE8Kow4grw45QdybCr8Okw6AYwqbDksO3ehvDpUPCgcKsKXbCiAwPC8K2w4LDvsOkw6nCjhPDpcOQADElWsOoU8KGR3HCtsOAwqd6wp_Dulp8w6LDsF_CtsK7Kk05wrMvwrLClMOgG2_Dn2sGPg').first_page } end.not_to raise_exception end end describe '#first_page' do it 'returns only the first page of a new sync' do vcr('sync_page')do expect(create_client.sync(initial: true).first_page).to be_a Contentful::SyncPage end end end describe '#each_page' do it 'iterates through sync pages' do sync = create_client.sync(initial: true) vcr('sync_page'){ vcr('sync_page_2'){ count = 0 sync.each_page do |page| expect(page).to be_a Contentful::SyncPage count += 1 end expect(count).to eq 2 }} end end describe '#next_sync_url' do it 'is empty if there are still more pages to request in the current sync' do expect(first_page.next_sync_url).to be_nil end it 'returns the url to continue the sync next time' do expect(last_page.next_sync_url).to be_a String end end describe '#completed?' do it 'will return true if no more pages to request in the current sync' do expect(first_page.next_sync_url).to be_falsey end it 'will return true if not all pages requested, yet' do expect(last_page.next_sync_url).to be_truthy end end describe '#each_item' do it 'will directly iterate through all resources' do sync = create_client.sync(initial: true) vcr('sync_page'){ vcr('sync_page_2'){ sync.each_item do |item| expect(item).to be_a Contentful::BaseResource end }} end end describe 'Resource parsing' do it 'will correctly parse the `file` field of an asset' do sync = create_client.sync(initial: true) vcr('sync_page') { asset = sync.first_page.items.select { |item| item.is_a?(Contentful::Asset) }.first expect(asset.file.file_name).to eq 'doge.jpg' expect(asset.file.content_type).to eq 'image/jpeg' expect(asset.file.details['image']['width']).to eq 5800 expect(asset.file.details['image']['height']).to eq 4350 expect(asset.file.details['size']).to eq 522943 expect(asset.file.url).to eq '//images.contentful.com/cfexampleapi/1x0xpXu4pSGS4OukSyWGUK/cc1239c6385428ef26f4180190532818/doge.jpg' } end end describe 'raw_mode' do before do @sync = create_client(raw_mode: true).sync(initial: true) end it 'should not fail' do vcr('sync_page_short') { expect { @sync.first_page }.not_to raise_error } end it 'should return a raw Response' do vcr('sync_page_short') { expect(@sync.first_page).to be_a Contentful::Response } end it 'should return JSON' do expected = { "sys" => {"type" => "Array"}, "items" => [ { "sys" => { "space" => { "sys" => { "type" => "Link", "linkType" => "Space", "id" => "cfexampleapi"} }, "type" => "Entry", "contentType" => { "sys" => { "type" => "Link", "linkType" => "ContentType", "id" => "1t9IbcfdCk6m04uISSsaIK" } }, "id" => "5ETMRzkl9KM4omyMwKAOki", "revision" => 2, "createdAt" => "2014-02-21T13:42:57.752Z", "updatedAt" => "2014-04-16T12:44:02.691Z" }, "fields" => { "name" => {"en-US"=>"London"}, "center" => { "en-US" => {"lat"=>51.508515, "lon"=>-0.12548719999995228} } } } ], "nextSyncUrl" => "https://cdn.contentful.com/spaces/cfexampleapi/environments/master/sync?sync_token=w5ZGw6JFwqZmVcKsE8Kow4grw45QdybCr8Okw6AYwqbDksO3ehvDpUPCgcKsKXbCiAwPC8K2w4LDvsOkw6nCjhPDpcOQADElWsOoU8KGR3HCtsOAwqd6wp_Dulp8w6LDsF_CtsK7Kk05wrMvwrLClMOgG2_Dn2sGPg" } vcr('sync_page_short') { expect(@sync.first_page.object).to eql expected } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/content_type_spec.rb
spec/content_type_spec.rb
require 'spec_helper' describe Contentful::ContentType do let(:content_type) { vcr('content_type') { create_client.content_type 'cat' } } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(content_type.sys).to be_a Hash expect(content_type.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(content_type.id).to eq 'cat' end it 'has #type' do expect(content_type.type).to eq 'ContentType' end end describe 'Properties' do it 'has #name' do expect(content_type.name).to eq 'Cat' end it 'has #description' do expect(content_type.description).to eq 'Meow.' end it 'has #fields' do expect(content_type.fields).to be_a Array expect(content_type.fields.first).to be_a Contentful::Field end it 'could have #display_field' do expect(content_type).to respond_to :display_field end end describe 'camel case' do it 'supports camel case' do vcr('content_type') { content_type = create_client(use_camel_case: true).content_type 'cat' expect(content_type.displayField).to eq 'name' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' SimpleCov.start require 'rspec' require 'contentful' require 'securerandom' require 'rr' Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |f| require f } RSpec.configure do |config| config.filter_run :focus => true config.run_all_when_everything_filtered = true end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/asset_spec.rb
spec/asset_spec.rb
require 'spec_helper' describe Contentful::Asset do let(:asset) { vcr('asset') { create_client.asset('nyancat') } } describe 'SystemProperties' do it 'has a #sys getter returning a hash with symbol keys' do expect(asset.sys).to be_a Hash expect(asset.sys.keys.sample).to be_a Symbol end it 'has #id' do expect(asset.id).to eq 'nyancat' end it 'has #type' do expect(asset.type).to eq 'Asset' end it 'has #space' do expect(asset.space).to be_a Contentful::Link end it 'has #created_at' do expect(asset.created_at).to be_a DateTime end it 'has #updated_at' do expect(asset.updated_at).to be_a DateTime end it 'has #revision' do expect(asset.revision).to eq 1 end end describe 'Fields' do it 'has #title' do expect(asset.title).to eq 'Nyan Cat' end it 'could have #description' do expect(asset).to respond_to :description end it 'has #file' do expect(asset.file).to be_a Contentful::File end end describe '#image_url' do it 'returns #url of #file without parameter' do expect(asset.image_url).to eq asset.file.url end it 'adds image options if given' do url = asset.image_url(width: 100, format: 'jpg', quality: 50, focus: 'top_right', fit: 'thumb', fl: 'progressive', background: 'rgb:ff0000') expect(url).to include asset.file.url expect(url).to include '?w=100&fm=jpg&q=50&f=top_right&bg=rgb%3Aff0000&fit=thumb&fl=progressive' end end describe '#url' do it 'returns #url of #file without parameter' do expect(asset.url).to eq asset.file.url end it 'adds image options if given' do url = asset.url(width: 100, format: 'jpg', quality: 50, focus: 'top_right', fit: 'thumb', fl: 'progressive', background: 'rgb:ff0000') expect(url).to include asset.file.url expect(url).to include '?w=100&fm=jpg&q=50&f=top_right&bg=rgb%3Aff0000&fit=thumb&fl=progressive' end end it 'can be marshalled' do marshalled = Marshal.dump(asset) unmarshalled = Marshal.load(marshalled) expect(unmarshalled.title).to eq 'Nyan Cat' expect(unmarshalled.file).to be_a Contentful::File end describe 'incoming links' do let(:client) { create_client } it 'will fetch entries referencing the asset using a query' do vcr('entry/search_link_to_asset') { entries = client.entries(links_to_asset: 'nyancat') expect(entries).not_to be_empty expect(entries.count).to eq 1 expect(entries.first.id).to eq 'nyancat' } end it 'will fetch entries referencing the entry using instance method' do vcr('entry/search_link_to_asset') { entries = asset.incoming_references client expect(entries).not_to be_empty expect(entries.count).to eq 1 expect(entries.first.id).to eq 'nyancat' } end end describe 'select operator' do let(:client) { create_client } context 'with sys sent' do it 'properly creates an entry' do vcr('asset/select_only_sys') { asset = client.assets(select: ['sys']).first expect(asset.fields).to be_empty expect(asset.sys).not_to be_empty } end it 'can contain only one field' do vcr('asset/select_one_field') { asset = client.assets(select: ['sys', 'fields.file']).first expect(asset.fields.keys).to eq([:file]) } end end context 'without sys sent' do it 'will enforce sys anyway' do vcr('asset/select_no_sys') { asset = client.assets(select: ['fields'], 'sys.id' => 'nyancat').first expect(asset.id).to eq 'nyancat' expect(asset.sys).not_to be_empty } end it 'works with empty array as well, as sys is enforced' do vcr('asset/select_empty_array') { asset = client.assets(select: [], 'sys.id' => 'nyancat').first expect(asset.id).to eq 'nyancat' expect(asset.sys).not_to be_empty } end end end describe 'issues' do it 'serializes files correctly for every locale - #129' do vcr('assets/issues_129') { client = create_client( space: 'bht13amj0fva', access_token: 'bb703a05e107148bed6ee246a9f6b3678c63fed7335632eb68fe1b689c801534' ) asset = client.assets('sys.id' => '14bZJKTr6AoaGyeg4kYiWq', locale: '*').first expect(asset.file).to be_a ::Contentful::File expect(asset.file.file_name).to eq 'Flag_of_the_United_States.svg' expect(asset.fields[:file]).to be_a ::Contentful::File expect(asset.fields[:file].file_name).to eq 'Flag_of_the_United_States.svg' expect(asset.fields('es')[:file]).to be_a ::Contentful::File expect(asset.fields('es')[:file].file_name).to eq 'Flag_of_Spain.svg' } end it 'properly serializes files for non-default locales on localized requests - jekyll-contentful-data-import #46' do vcr('assets/issues_jekyll_46') { client = create_client( space: 'bht13amj0fva', access_token: 'bb703a05e107148bed6ee246a9f6b3678c63fed7335632eb68fe1b689c801534', ) asset = client.assets('sys.id' => '14bZJKTr6AoaGyeg4kYiWq', locale: 'es').first expect(asset.file).to be_a ::Contentful::File expect(asset.file.file_name).to eq 'Flag_of_Spain.svg' } end end describe 'camelCase' do it 'properties now are accessed with camelcase' do vcr('asset') { asset = create_client(use_camel_case: true).asset('nyancat') expect(asset.file.fileName).to eq 'Nyan_cat_250px_frame.png' } end end describe 'tags metadata' do let(:asset_id) { '686aLBcjj1f47uFWxrepj6' } it 'can load an asset with tags' do vcr('asset/with_tags') { expect { asset = create_client.asset(asset_id) }.not_to raise_error } end it 'hydrates tags' do vcr('asset/with_tags') { asset = create_client.asset(asset_id) expect(asset._metadata[:tags].first).to be_a Contentful::Link } end it 'loads tag links with their proper attributes' do vcr('asset/with_tags') { asset = create_client.asset(asset_id) tag = asset._metadata[:tags].first expect(tag.id).to eq 'mobQa' expect(tag.link_type).to eq 'Tag' } end end describe 'concepts metadata' do let(:asset_id) { '3v0s5QAHjGFqCS5aBfd1dX' } it 'can load an asset with concepts' do vcr('asset/with_concepts') { expect { asset = create_client.asset(asset_id) }.not_to raise_error } end it 'hydrates concepts' do vcr('asset/with_concepts') { asset = create_client.asset(asset_id) expect(asset._metadata[:concepts].first).to be_a Contentful::Link } end it 'loads concept links with their proper attributes' do vcr('asset/with_concepts') { asset = create_client.asset(asset_id) concept = asset._metadata[:concepts].first expect(concept.id).to eq '5iRG7dAusVFUOh9SrexDqQ' expect(concept.link_type).to eq 'TaxonomyConcept' } end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/support/json_responses.rb
spec/support/json_responses.rb
require 'multi_json' def raw_fixture(which, status = 200, _as_json = false, headers = {}) object = Object.new allow(object).to receive(:status) { status } allow(object).to receive(:headers) { headers } allow(object).to receive(:to_s) { File.read File.dirname(__FILE__) + "/../fixtures/json_responses/#{which}.json" } allow(object).to receive(:body) { object.to_s } allow(object).to receive(:[]) { |key| object.headers[key] } object end def json_fixture(which, _as_json = false) MultiJson.load( File.read File.dirname(__FILE__) + "/../fixtures/json_responses/#{which}.json" ) end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/support/vcr.rb
spec/support/vcr.rb
require 'vcr' VCR.configure do |c| c.cassette_library_dir = 'spec/fixtures/vcr_cassettes' c.ignore_localhost = true c.hook_into :webmock c.default_cassette_options = { record: :once } end def vcr(name, &block) VCR.use_cassette(name, &block) end def expect_vcr(name, &block) expect { VCR.use_cassette(name, &block) } end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/spec/support/client.rb
spec/support/client.rb
def create_client(options = {}) Contentful::Client.new({ space: 'cfexampleapi', access_token: 'b4c0n73n7fu1', }.merge(options)) end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/examples/custom_classes.rb
examples/custom_classes.rb
require 'contentful' # You can define your own custom classes that inherit from Contentful::Entry. # This allows you to define custom behaviour, for example, in this case, we want # the :country field to act as a Contentful::Locale class MyResource < Contentful::Entry def country(locale = nil) @country ||= Contentful::Locale.new(fields(locale)[:country]) end end res = MyResource.new('fields' => { 'some' => 'value', 'age' => '25', 'country' => { 'code' => 'de', 'name' => 'Deutschland' }, 'unknown_property' => 'ignored' }) p res.some # => "value" p res.age # => 25 p res.country # #<Contentful::Locale: ... p res.unknown_property # NoMethodError # To then have it mapped automatically from the client, # upon client instantiation, you set the :entry_mapping for your ContentType. client = Contentful::Client.new( space: 'your_space_id', access_token: 'your_access_token', entry_mapping: { 'myResource' => MyResource } ) # We request the entries, entries of the 'myResource` content type, # will return MyResource class objects, while others will remain Contentful::Entry. client.entries.each { |e| puts e } # => <Contentful::Entry[other_content_type] id='foobar'> # => <MyResource[myResource] id='baz'>
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/examples/raise_errors.rb
examples/raise_errors.rb
require 'contentful' client = Contentful::Client.new( space: 'cfexampleapi', access_token: 'b4c0n73n7fu1', ) begin p client.asset 'not found' rescue => error p error end client2 = Contentful::Client.new( space: 'cfexampleapi', access_token: 'b4c0n73n7fu1', raise_errors: false, ) p client2.asset 'not found'
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/examples/example_queries.rb
examples/example_queries.rb
require 'contentful' client = Contentful::Client.new( space: 'cfexampleapi', access_token: 'b4c0n73n7fu1', ) p client.space p client.content_types p client.entry 'nyancat', locale: 'tlh' p client.entries( 'content_type' => 'cat', 'fields.likes' => 'lasagna', ) p client.entries( query: 'bacon', ) p client.content_types( order: '-sys.updatedAt', limit: 3, )
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/examples/raw_mode.rb
examples/raw_mode.rb
require 'contentful' client = Contentful::Client.new( space: 'cfexampleapi', access_token: 'b4c0n73n7fu1', raw_mode: true, ) entry = client.entry 'nyancat' p entry.is_a? Contentful::Resource # false p entry.is_a? Contentful::Response # true p entry.status p entry puts entry.raw
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful.rb
lib/contentful.rb
require 'contentful/version' require 'contentful/support' require 'contentful/client'
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/entry.rb
lib/contentful/entry.rb
require_relative 'error' require_relative 'fields_resource' require_relative 'content_type_cache' require_relative 'resource_references' require_relative 'includes' module Contentful # Resource class for Entry. # @see _ https://www.contentful.com/developers/documentation/content-delivery-api/#entries class Entry < FieldsResource include Contentful::ResourceReferences # Returns true for resources that are entries def entry? true end private def coerce(field_id, value, includes, errors, entries = {}) if Support.link?(value) return nil if Support.unresolvable?(value, errors) return build_nested_resource(value, includes, entries, errors) end return coerce_link_array(value, includes, errors, entries) if Support.link_array?(value) content_type_key = Support.snakify('contentType', @configuration[:use_camel_case]) content_type = ContentTypeCache.cache_get(sys[:space].id, sys[content_type_key.to_sym].id) unless content_type.nil? content_type_field = content_type.field_for(field_id) coercion_configuration = @configuration.merge( includes_for_single: @configuration.fetch(:includes_for_single, Includes.new) + includes, _entries_cache: entries, localized: localized, depth: @depth, errors: errors ) return content_type_field.coerce(value, coercion_configuration) unless content_type_field.nil? end super(field_id, value, includes, errors, entries) end def coerce_link_array(value, includes, errors, entries) items = [] value.each do |link| nested_resource = build_nested_resource(link, includes, entries, errors) unless Support.unresolvable?(link, errors) items << nested_resource unless nested_resource.nil? end items end # Maximum include depth is 10 in the API, but we raise it to 20 (by default), # in case one of the included items has a reference in an upper level, # so we can keep the include chain for that object as well # Any included object after the maximum include resolution depth will be just a Link def build_nested_resource(value, includes, entries, errors) if @depth < @configuration.fetch(:max_include_resolution_depth, 20) resource = includes.find_link(value) return resolve_include(resource, includes, entries, errors) unless resource.nil? end build_link(value) end def resolve_include(resource, includes, entries, errors) require_relative 'resource_builder' ResourceBuilder.new( resource, @configuration.merge( includes_for_single: @configuration.fetch(:includes_for_single, Includes.new) + includes, _entries_cache: entries ), localized, @depth + 1, errors ).run end def known_link?(name) field_name = name.to_sym return true if known_contentful_object?(fields[field_name]) fields[field_name].is_a?(Enumerable) && fields[field_name].any? { |object| known_contentful_object?(object) } end def known_contentful_object?(object) (object.is_a?(Contentful::Entry) || object.is_a?(Contentful::Asset)) end def method_missing(name, *args, &block) return empty_field_error(name) if content_type_field?(name) super end def respond_to_missing?(name, include_private = false) content_type_field?(name) || super end protected def content_type_field?(name) content_type_key = Support.snakify('contentType', @configuration[:use_camel_case]) content_type = ContentTypeCache.cache_get( sys[:space].id, sys[content_type_key.to_sym].id ) return false if content_type.nil? !content_type.field_for(name).nil? end def empty_field_error(name) return nil unless @configuration[:raise_for_empty_fields] fail EmptyFieldError, name end def repr_name content_type_key = Support.snakify('contentType', @configuration[:use_camel_case]).to_sym "#{super}[#{sys[content_type_key].id}]" end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/version.rb
lib/contentful/version.rb
# Contentful Namespace module Contentful # Gem Version VERSION = '2.19.0' end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/content_type.rb
lib/contentful/content_type.rb
require_relative 'base_resource' require_relative 'field' require_relative 'support' module Contentful # Resource Class for Content Types # https://www.contentful.com/developers/documentation/content-delivery-api/#content-types class ContentType < BaseResource attr_reader :name, :description, :fields, :display_field def initialize(item, *) super @name = item.fetch('name', nil) @description = item.fetch('description', nil) @fields = item.fetch('fields', []).map { |field| Field.new(field) } @display_field = item.fetch('displayField', nil) end # Field definition for field def field_for(field_id) fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) } end alias displayField display_field protected def repr_name "#{super}[#{name}]" end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/resource_builder.rb
lib/contentful/resource_builder.rb
require_relative 'error' require_relative 'space' require_relative 'content_type' require_relative 'entry' require_relative 'asset' require_relative 'array' require_relative 'link' require_relative 'deleted_entry' require_relative 'deleted_asset' require_relative 'locale' require_relative 'includes' require_relative 'taxonomy_concept' require_relative 'taxonomy_concept_scheme' module Contentful # Transforms a Contentful::Response into a Contentful::Resource or a Contentful::Error # See example/resource_mapping.rb for advanced usage class ResourceBuilder # Default Resource Mapping # @see _ README for more information on Resource Mapping DEFAULT_RESOURCE_MAPPING = { 'Space' => Space, 'ContentType' => ContentType, 'Entry' => Entry, 'Asset' => Asset, 'Array' => Array, 'Link' => Link, 'DeletedEntry' => DeletedEntry, 'DeletedAsset' => DeletedAsset, 'Locale' => Locale, 'TaxonomyConcept' => TaxonomyConcept, 'TaxonomyConceptScheme' => TaxonomyConceptScheme }.freeze # Default Entry Mapping # @see _ README for more information on Entry Mapping DEFAULT_ENTRY_MAPPING = {}.freeze # Buildable Resources BUILDABLES = %w[Entry Asset ContentType Space DeletedEntry DeletedAsset Locale TaxonomyConcept TaxonomyConceptScheme].freeze attr_reader :json, :default_locale, :endpoint, :depth, :localized, :resource_mapping, :entry_mapping, :resource, :query def initialize(json, configuration = {}, localized = false, depth = 0, errors = [], query = {}) @json = json @default_locale = configuration.fetch(:default_locale, ::Contentful::Client::DEFAULT_CONFIGURATION[:default_locale]) @resource_mapping = default_resource_mapping.merge(configuration.fetch(:resource_mapping, {})) @entry_mapping = default_entry_mapping.merge(configuration.fetch(:entry_mapping, {})) @includes_for_single = configuration.fetch(:includes_for_single, Includes.new) @localized = localized @depth = depth @endpoint = configuration.fetch(:endpoint, nil) @configuration = configuration @resource_cache = configuration[:_entries_cache] || {} @errors = errors @query = query end # Starts the parsing process. # # @return [Contentful::Resource, Contentful::Error] def run return build_array if array? build_single rescue UnparsableResource => error error end private def build_array includes = fetch_includes || @includes_for_single errors = fetch_errors || @errors result = json['items'].map do |item| next if Support.unresolvable?(item, errors) build_item(item, includes, errors) end array_class = fetch_array_class array_class.new(json.merge('items' => result), @configuration, endpoint, query) end def build_single return if Support.unresolvable?(json, @errors) includes = @includes_for_single build_item(json, includes, @errors) end def build_item(item, includes = Includes.new, errors = []) item_type = BUILDABLES.detect { |b| b == item['sys']['type'] } fail UnparsableResource, 'Item type is not known, could not parse' if item_type.nil? item_class = resource_class(item) reuse_entries = @configuration.fetch(:reuse_entries, false) resource_cache = @resource_cache ? @resource_cache : {} id = "#{item['sys']['type']}:#{item['sys']['id']}" resource = if reuse_entries && resource_cache.key?(id) resource_cache[id] else item_class.new(item, @configuration, localized?, includes, resource_cache, depth, errors) end resource end def fetch_includes Includes.from_response(json) end def fetch_errors json.fetch('errors', []) end def resource_class(item) return fetch_custom_resource_class(item) if %w[Entry DeletedEntry Asset DeletedAsset].include?(item['sys']['type']) resource_mapping[item['sys']['type']] end def fetch_custom_resource_class(item) case item['sys']['type'] when 'Entry' resource_class = entry_mapping[item['sys']['contentType']['sys']['id']] return resource_class unless resource_class.nil? fetch_custom_resource_mapping(item, 'Entry', Entry) when 'Asset' fetch_custom_resource_mapping(item, 'Asset', Asset) when 'DeletedEntry' fetch_custom_resource_mapping(item, 'DeletedEntry', DeletedEntry) when 'DeletedAsset' fetch_custom_resource_mapping(item, 'DeletedAsset', DeletedAsset) end end def fetch_custom_resource_mapping(item, type, default_class) resources = resource_mapping[type] return default_class if resources.nil? return resources if resources.is_a?(Class) return resources[item] if resources.respond_to?(:call) default_class end def fetch_array_class return SyncPage if sync? ::Contentful::Array end def localized? return true if @localized return true if array? && sync? false end def array? json.fetch('sys', {}).fetch('type', '') == 'Array' end def sync? json.fetch('nextSyncUrl', nil) || json.fetch('nextPageUrl', nil) end # The default mapping for #detect_resource_class def default_resource_mapping DEFAULT_RESOURCE_MAPPING end # The default entry mapping def default_entry_mapping DEFAULT_ENTRY_MAPPING end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/array_like.rb
lib/contentful/array_like.rb
# frozen_string_literal: true module Contentful # Useful methods for array-like resources that can be included if an # :items property exists module ArrayLike include Enumerable # Returns true for array-like resources # # @return [true] def array? true end # Delegates to items#each # # @yield [Contentful::Entry, Contentful::Asset] def each_item(&block) items.each(&block) end alias each each_item # Delegates to items#empty? # # @return [Boolean] def empty? items.empty? end # Delegetes to items#size # # @return [Number] def size items.size end alias length size # Delegates to items#[] # # @return [Contentful::Entry, Contentful::Asset] def [](*args) items[*args] end # Delegates to items#last # # @return [Contentful::Entry, Contentful::Asset] def last items.last end # Delegates to items#to_ary # # @return [Contentful::Entry, Contentful::Asset] def to_ary items end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/deleted_entry.rb
lib/contentful/deleted_entry.rb
require_relative 'base_resource' module Contentful # Resource class for deleted entries # https://www.contentful.com/developers/documentation/content-delivery-api/http/#sync-item-types class DeletedEntry < BaseResource; end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/base_resource.rb
lib/contentful/base_resource.rb
# frozen_string_literal: true require_relative 'support' module Contentful # Base definition of a Contentful Resource containing Sys properties class BaseResource attr_reader :raw, :default_locale, :sys, :_metadata # rubocop:disable Metrics/ParameterLists def initialize(item, configuration = {}, _localized = false, _includes = Includes.new, entries = {}, depth = 0, _errors = []) entries["#{item['sys']['type']}:#{item['sys']['id']}"] = self if entries && item.key?('sys') @raw = item @default_locale = configuration[:default_locale] @depth = depth @configuration = configuration @sys = hydrate_sys @_metadata = hydrate_metadata define_sys_methods! end # @private def inspect "<#{repr_name} id='#{sys[:id]}'>" end # Definition of equality def ==(other) self.class == other.class && sys[:id] == other.sys[:id] end # @private def marshal_dump entry_mapping = @configuration[:entry_mapping].each_with_object({}) do |(k, v), res| res[k] = v.to_s end { # loggers usually have a file handle that can't be marshalled, so let's not return that configuration: @configuration.merge(entry_mapping: entry_mapping, logger: nil), raw: raw } end # @private def marshal_load(raw_object) raw_object[:configuration][:entry_mapping] = raw_object[:configuration].fetch(:entry_mapping, {}).each_with_object({}) do |(k, v), res| begin v = v.to_s unless v.is_a?(::String) res[k] = v.split('::').inject(Object) { |o, c| o.const_get c } rescue next end end @raw = raw_object[:raw] @configuration = raw_object[:configuration] @default_locale = @configuration[:default_locale] @sys = hydrate_sys @_metadata = hydrate_metadata @depth = 0 define_sys_methods! end # Issues the request that was made to fetch this response again. # Only works for Entry, Asset, ContentType and Space def reload(client = nil) return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil? false end private def define_sys_methods! @sys.each do |k, v| define_singleton_method(k) { v } unless self.class.method_defined?(k) end end LINKS = %w[space contentType environment].freeze TIMESTAMPS = %w[createdAt updatedAt deletedAt].freeze def hydrate_sys result = {} raw.fetch('sys', {}).each do |k, v| if LINKS.include?(k) v = build_link(v) elsif TIMESTAMPS.include?(k) v = DateTime.parse(v) end result[Support.snakify(k, @configuration[:use_camel_case]).to_sym] = v end result end def hydrate_metadata result = {} raw.fetch('metadata', {}).each do |k, v| v = v.map { |item| build_link(item) } if %w[tags concepts].include?(k) result[Support.snakify(k, @configuration[:use_camel_case]).to_sym] = v end result end protected def repr_name self.class end def internal_resource_locale sys.fetch(:locale, nil) || default_locale end def build_link(item) require_relative 'link' ::Contentful::Link.new(item, @configuration) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/sync.rb
lib/contentful/sync.rb
require_relative 'resource_builder' require_relative 'deleted_entry' require_relative 'deleted_asset' require_relative 'sync_page' module Contentful # Resource class for Sync. # @see _ https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/synchronization class Sync attr_reader :next_sync_url def initialize(client, options_or_url) @client = client @next_sync_url = nil @first_page_options_or_url = options_or_url end # Iterates over all pages of the current sync # # @note Please Keep in Mind: Iterating fires a new request for each page # # @yield [Contentful::SyncPage] def each_page page = first_page yield page if block_given? until completed? page = page.next_page yield page if block_given? end end # Returns the first sync result page # # @return [Contentful::SyncPage] def first_page get(@first_page_options_or_url) end # Returns false as long as last sync page has not been reached # # @return [Boolean] def completed? # rubocop:disable Style/DoubleNegation !!next_sync_url # rubocop:enable Style/DoubleNegation end # Directly iterates over all resources that have changed # # @yield [Contentful::Entry, Contentful::Asset] def each_item(&block) each_page do |page| page.each_item(&block) end end # @private def get(options_or_url) page = fetch_page(options_or_url) return page if @client.configuration[:raw_mode] link_page_to_sync! page update_sync_state_from! page page end private def fetch_page(options_or_url) return Request.new(@client, options_or_url).get if options_or_url.is_a? String Request.new(@client, @client.environment_url('/sync'), options_or_url).get end def link_page_to_sync!(page) page.instance_variable_set :@sync, self end def update_sync_state_from!(page) @next_sync_url = page.next_sync_url end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/content_type_cache.rb
lib/contentful/content_type_cache.rb
module Contentful # Cache for Content Types class ContentTypeCache @cache = {} class << self attr_reader :cache end # Clears the Content Type Cache def self.clear! @cache = {} end # Gets a Content Type from the Cache def self.cache_get(space_id, content_type_id) @cache.fetch(space_id, {}).fetch(content_type_id.to_sym, nil) end # Sets a Content Type in the Cache def self.cache_set(space_id, content_type_id, klass) @cache[space_id] ||= {} @cache[space_id][content_type_id.to_sym] = klass end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/coercions.rb
lib/contentful/coercions.rb
require_relative 'location' require_relative 'link' module Contentful # Basic Coercion class BaseCoercion attr_reader :value, :options def initialize(value, options = {}) @value = value @options = options end # Coerces value def coerce(*) value end end # Coercion for String Types class StringCoercion < BaseCoercion # Coerces value to String def coerce(*) value.to_s end end # Coercion for Text Types class TextCoercion < StringCoercion; end # Coercion for Symbol Types class SymbolCoercion < StringCoercion; end # Coercion for Integer Types class IntegerCoercion < BaseCoercion # Coerces value to Integer def coerce(*) value.to_i end end # Coercion for Float Types class FloatCoercion < BaseCoercion # Coerces value to Float def coerce(*) value.to_f end end # Coercion for Boolean Types class BooleanCoercion < BaseCoercion # Coerces value to Boolean def coerce(*) # rubocop:disable Style/DoubleNegation !!value # rubocop:enable Style/DoubleNegation end end # Coercion for Date Types class DateCoercion < BaseCoercion # Coerces value to DateTime def coerce(*) return nil if value.nil? return value if value.is_a?(Date) DateTime.parse(value) end end # Coercion for Location Types class LocationCoercion < BaseCoercion # Coerces value to Location def coerce(*) Location.new(value) end end # Coercion for Object Types class ObjectCoercion < BaseCoercion # Coerces value to hash, symbolizing each key def coerce(*) JSON.parse(JSON.dump(value), symbolize_names: true) end end # Coercion for Link Types # Nothing should be done here as include resolution is handled within # entries due to depth handling (explained within Entry). # Only present as a placeholder for proper resolution within ContentType. class LinkCoercion < BaseCoercion; end # Coercion for Array Types class ArrayCoercion < BaseCoercion # Coerces value for each element def coerce(*) value.map do |e| options[:coercion_class].new(e).coerce end end end # Coercion for RichText Types class RichTextCoercion < BaseCoercion # Resolves includes and removes unresolvable nodes def coerce(configuration) coerce_block(value, configuration) end private def link?(node) !node['data'].is_a?(::Contentful::Entry) && !node.fetch('data', {}).empty? && node['data']['target'] end def content_block?(node) !node.fetch('content', []).empty? end def coerce_block(block, configuration) return block unless block.is_a?(Hash) && block.key?('content') invalid_nodes = [] coerced_nodes = {} block['content'].each_with_index do |node, index| if link?(node) link = coerce_link(node, configuration) if !link.nil? node['data']['target'] = link else invalid_nodes << index end elsif content_block?(node) coerced_nodes[index] = coerce_block(node, configuration) end end coerced_nodes.each do |index, coerced_node| block['content'][index] = coerced_node end invalid_nodes.each do |index| block['content'].delete_at(index) end block end def coerce_link(node, configuration) return node unless node.key?('data') && node['data'].key?('target') return node['data']['target'] unless node['data']['target'].is_a?(::Hash) return node unless node['data']['target']['sys']['type'] == 'Link' return nil if Support.unresolvable?(node['data']['target'], configuration[:errors]) resource = configuration[:includes_for_single].find_link(node['data']['target']) # Resource is valid but unreachable return Link.new(node['data']['target'], configuration) if resource.nil? ResourceBuilder.new( resource, configuration, configuration[:localized], configuration[:depth] + 1, configuration[:errors] ).run end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/field.rb
lib/contentful/field.rb
require_relative 'location' require_relative 'coercions' module Contentful # A ContentType's field schema # See https://www.contentful.com/developers/documentation/content-management-api/#resources-content-types-fields class Field # Coercions from Contentful Types to Ruby native types KNOWN_TYPES = { 'String' => StringCoercion, 'Text' => TextCoercion, 'Symbol' => SymbolCoercion, 'Integer' => IntegerCoercion, 'Number' => FloatCoercion, 'Boolean' => BooleanCoercion, 'Date' => DateCoercion, 'Location' => LocationCoercion, 'Object' => ObjectCoercion, 'Array' => ArrayCoercion, 'Link' => LinkCoercion, 'RichText' => RichTextCoercion } attr_reader :raw, :id, :name, :type, :link_type, :items, :required, :localized def initialize(json) @raw = json @id = json.fetch('id', nil) @name = json.fetch('name', nil) @type = json.fetch('type', nil) @link_type = json.fetch('linkType', nil) @items = json.key?('items') ? Field.new(json.fetch('items', {})) : nil @required = json.fetch('required', false) @localized = json.fetch('localized', false) end # Coerces value to proper type def coerce(value, configuration) return value if type.nil? return value if value.nil? options = {} options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil? KNOWN_TYPES[type].new(value, options).coerce(configuration) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/array.rb
lib/contentful/array.rb
require_relative 'base_resource' require_relative 'array_like' require_relative 'includes' module Contentful # Resource Class for Arrays (e.g. search results) # @see _ https://www.contentful.com/developers/documentation/content-delivery-api/#arrays # @note It also provides an #each method and includes Ruby's Enumerable module (gives you methods like #min, #first, etc) class Array < BaseResource # @private DEFAULT_LIMIT = 100 include Contentful::ArrayLike attr_reader :total, :limit, :skip, :items, :endpoint, :query def initialize(item = nil, configuration = { default_locale: Contentful::Client::DEFAULT_CONFIGURATION[:default_locale] }, endpoint = '', query = {}, *) super(item, configuration) @endpoint = endpoint @total = item.fetch('total', nil) @limit = item.fetch('limit', nil) @skip = item.fetch('skip', nil) @items = item.fetch('items', []) @query = query end # @private def marshal_dump super.merge(endpoint: endpoint, query: query) end # @private def marshal_load(raw_object) super @endpoint = raw_object[:endpoint] @total = raw.fetch('total', nil) @limit = raw.fetch('limit', nil) @skip = raw.fetch('skip', nil) @query = raw_object[:query] @items = raw.fetch('items', []).map do |item| require_relative 'resource_builder' ResourceBuilder.new( item.raw, raw_object[:configuration].merge(includes_for_single: Includes.from_response(raw, false)), item.respond_to?(:localized) ? item.localized : false, 0, raw_object[:configuration][:errors] || [] ).run end end # @private def inspect "<#{repr_name} total=#{total} skip=#{skip} limit=#{limit}>" end # Simplifies pagination # # @return [Contentful::Array, false] def next_page(client = nil) return false if client.nil? return false if items.first.nil? new_skip = (skip || 0) + (limit || DEFAULT_LIMIT) plurals = { 'Space' => 'spaces', 'ContentType' => 'content_types', 'Entry' => 'entries', 'Asset' => 'assets', 'Locale' => 'locales', 'TaxonomyConcept' => 'taxonomy_concepts' } client.public_send(plurals[items.first.type], query.merge(limit: limit, skip: new_skip)) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/file.rb
lib/contentful/file.rb
module Contentful # An Assets's file info class File def initialize(json, configuration) @configuration = configuration define_fields!(json) end private def define_fields!(json) json.each do |k, v| define_singleton_method Support.snakify(k, @configuration[:use_camel_case]) do v end end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/response.rb
lib/contentful/response.rb
require_relative 'error' require 'multi_json' require 'zlib' module Contentful # An object representing an answer by the contentful service. It is later used # to build a Resource, which is done by the ResourceBuilder. # # The Response parses the http response (as returned by the underlying http library) to # a JSON object. Responses can be asked the following methods: # - #raw (raw HTTP response by the HTTP library) # - #object (the parsed JSON object) # - #request (the request the response is refering to) # # It also sets a #status which can be one of: # - :ok (seems to be a valid resource object) # - :contentful_error (valid error object) # - :not_contentful (valid json, but missing the contentful's sys property) # - :unparsable_json (invalid json) # # Error Repsonses also contain a: # - :error_message class Response attr_reader :raw, :object, :status, :error_message, :request def initialize(raw, request = nil) @raw = raw @request = request @status = :ok if valid_http_response? parse_json! elsif no_content_response? @status = :no_content elsif invalid_response? parse_contentful_error elsif service_unavailable_response? service_unavailable_error else parse_http_error end end # Returns the JSON body of the response def load_json MultiJson.load(unzip_response(raw)) end private def error_object? object['sys']['type'] == 'Error' end def parse_contentful_error @object = load_json @error_message = object['message'] if error_object? parse_http_error end def valid_http_response? [200, 201].include?(raw.status) end def service_unavailable_response? @raw.status == 503 end def service_unavailable_error @status = :error @error_message = '503 - Service Unavailable' @object = Error[@raw.status].new(self) end def parse_http_error @status = :error @object = Error[raw.status].new(self) end def invalid_response? [400, 404].include?(raw.status) end def no_content_response? raw.to_s == '' && raw.status == 204 end def parse_json! @object = load_json rescue MultiJson::LoadError => error @error_message = error.message @status = :error UnparsableJson.new(self) end def unzip_response(response) parsed_response = response.to_s if response.headers['Content-Encoding'].eql?('gzip') sio = StringIO.new(parsed_response) gz = Zlib::GzipReader.new(sio) gz.read else parsed_response end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/taxonomy_concept.rb
lib/contentful/taxonomy_concept.rb
require_relative 'base_resource' module Contentful # Resource class for TaxonomyConcept. # @see _ https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/taxonomy/concept class TaxonomyConcept < BaseResource attr_reader :uri, :notations, :broader, :related, :concept_schemes def initialize(item, *) super @uri = item.fetch('uri', nil) @notations = item.fetch('notations', []) @broader = item.fetch('broader', []) @related = item.fetch('related', []) @concept_schemes = item.fetch('conceptSchemes', []) end # Returns true for resources that are taxonomy concepts def taxonomy_concept? true end # Returns false for resources that are not entries def entry? false end # Returns false for resources that are not assets def asset? false end # Access localized fields def pref_label(locale = nil) locale ||= default_locale pref_label = raw.fetch('prefLabel', {}) pref_label.is_a?(Hash) ? pref_label.fetch(locale.to_s, nil) : pref_label end def alt_labels(locale = nil) locale ||= default_locale alt_labels = raw.fetch('altLabels', {}) alt_labels.is_a?(Hash) ? alt_labels.fetch(locale.to_s, []) : alt_labels end def hidden_labels(locale = nil) locale ||= default_locale hidden_labels = raw.fetch('hiddenLabels', {}) hidden_labels.is_a?(Hash) ? hidden_labels.fetch(locale.to_s, []) : hidden_labels end def note(locale = nil) locale ||= default_locale note = raw.fetch('note', {}) note.is_a?(Hash) ? note.fetch(locale.to_s, '') : note end def change_note(locale = nil) locale ||= default_locale change_note = raw.fetch('changeNote', {}) change_note.is_a?(Hash) ? change_note.fetch(locale.to_s, '') : change_note end def definition(locale = nil) locale ||= default_locale definition = raw.fetch('definition', {}) definition.is_a?(Hash) ? definition.fetch(locale.to_s, '') : definition end def editorial_note(locale = nil) locale ||= default_locale editorial_note = raw.fetch('editorialNote', {}) editorial_note.is_a?(Hash) ? editorial_note.fetch(locale.to_s, '') : editorial_note end def example(locale = nil) locale ||= default_locale example = raw.fetch('example', {}) example.is_a?(Hash) ? example.fetch(locale.to_s, '') : example end def history_note(locale = nil) locale ||= default_locale history_note = raw.fetch('historyNote', {}) history_note.is_a?(Hash) ? history_note.fetch(locale.to_s, '') : history_note end def scope_note(locale = nil) locale ||= default_locale scope_note = raw.fetch('scopeNote', {}) scope_note.is_a?(Hash) ? scope_note.fetch(locale.to_s, '') : scope_note end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/location.rb
lib/contentful/location.rb
module Contentful # Location Field Type # You can directly query for them: https://www.contentful.com/developers/documentation/content-delivery-api/#search-filter-geo class Location attr_reader :lat, :lon alias latitude lat alias longitude lon def initialize(json) @lat = json.fetch('lat', nil) @lon = json.fetch('lon', nil) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/link.rb
lib/contentful/link.rb
require_relative 'base_resource' module Contentful # Resource Class for Links # https://www.contentful.com/developers/documentation/content-delivery-api/#links class Link < BaseResource # Queries contentful for the Resource the Link is refering to # Takes an optional query hash def resolve(client, query = {}) id_and_query = [(id unless link_type == 'Space')].compact + [query] client.public_send( Contentful::Support.snakify(link_type).to_sym, *id_and_query ) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/taxonomy_concept_scheme.rb
lib/contentful/taxonomy_concept_scheme.rb
require_relative 'base_resource' module Contentful # Resource class for TaxonomyConceptScheme. # @see _ https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/taxonomy/concept-scheme class TaxonomyConceptScheme < BaseResource attr_reader :uri, :top_concepts, :concepts, :total_concepts def initialize(item, *) super @uri = item.fetch('uri', nil) @top_concepts = item.fetch('topConcepts', []) @concepts = item.fetch('concepts', []) @total_concepts = item.fetch('totalConcepts', 0) end # Returns true for resources that are taxonomy concept schemes def taxonomy_concept_scheme? true end # Returns false for resources that are not taxonomy concepts def taxonomy_concept? false end # Returns false for resources that are not entries def entry? false end # Returns false for resources that are not assets def asset? false end # Access localized fields def pref_label(locale = nil) locale ||= default_locale pref_label = raw.fetch('prefLabel', {}) pref_label.is_a?(Hash) ? pref_label.fetch(locale.to_s, nil) : pref_label end def definition(locale = nil) locale ||= default_locale definition = raw.fetch('definition', {}) definition.is_a?(Hash) ? definition.fetch(locale.to_s, '') : definition end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/locale.rb
lib/contentful/locale.rb
require_relative 'base_resource' module Contentful # A Locale definition as included in Space # Read more about Localization at https://www.contentful.com/developers/documentation/content-delivery-api/#i18n class Locale < BaseResource attr_reader :code, :name, :default, :fallback_code def initialize(item, *) @code = item.fetch('code', nil) @name = item.fetch('name', nil) @default = item.fetch('default', false) @fallback_code = item.fetch('fallbackCode', nil) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/resource_references.rb
lib/contentful/resource_references.rb
module Contentful # Method to retrieve references (incoming links) for a given entry or asset module ResourceReferences # Gets a collection of entries which links to current entry # # @param [Contentful::Client] client # @param [Hash] query # # @return [Contentful::Array<Contentful::Entry>, false] def incoming_references(client = nil, query = {}) return false unless client query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id) client.entries(query) end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/client.rb
lib/contentful/client.rb
require_relative 'request' require_relative 'response' require_relative 'resource_builder' require_relative 'sync' require_relative 'content_type_cache' require 'http' require 'logger' require 'rbconfig' module Contentful # The client object is initialized with a space and a key and then used # for querying resources from this space. # See README for details class Client # Default configuration for Contentful::Client DEFAULT_CONFIGURATION = { secure: true, raise_errors: true, raise_for_empty_fields: true, dynamic_entries: :manual, api_url: 'cdn.contentful.com', api_version: 1, environment: 'master', authentication_mechanism: :header, resource_builder: ResourceBuilder, resource_mapping: {}, entry_mapping: {}, default_locale: 'en-US', raw_mode: false, gzip_encoded: true, logger: false, proxy_host: nil, proxy_username: nil, proxy_password: nil, proxy_port: nil, timeout_connect: nil, timeout_read: nil, timeout_write: nil, max_rate_limit_retries: 1, max_rate_limit_wait: 60, max_include_resolution_depth: 20, use_camel_case: false, application_name: nil, application_version: nil, integration_name: nil, integration_version: nil, http_instrumenter: nil } attr_reader :configuration, :logger, :proxy # Wraps the actual HTTP request via proxy # @private def self.get_http(url, query, headers = {}, proxy = {}, timeout = {}, instrumenter) http = HTTP[headers] http = http.timeout(timeout) if timeout.any? http = http.use(instrumentation: { instrumenter: instrumenter }) if instrumenter if proxy[:host] http.via(proxy[:host], proxy[:port], proxy[:username], proxy[:password]).get(url, params: query) else http.get(url, params: query) end end # @see _ https://github.com/contentful/contentful.rb#client-configuration-options # @param [Hash] given_configuration # @option given_configuration [String] :space Required # @option given_configuration [String] :access_token Required # @option given_configuration [String] :api_url Modifying this to 'preview.contentful.com' gives you access to our Preview API # @option given_configuration [String] :api_version # @option given_configuration [String] :default_locale # @option given_configuration [String] :proxy_host # @option given_configuration [String] :proxy_username # @option given_configuration [String] :proxy_password # @option given_configuration [Number] :proxy_port # @option given_configuration [Number] :timeout_read # @option given_configuration [Number] :timeout_write # @option given_configuration [Number] :timeout_connect # @option given_configuration [Number] :max_rate_limit_retries # @option given_configuration [Number] :max_rate_limit_wait # @option given_configuration [Number] :max_include_resolution_depth # @option given_configuration [Boolean] :use_camel_case # @option given_configuration [Boolean] :gzip_encoded # @option given_configuration [Boolean] :raw_mode # @option given_configuration [false, ::Logger] :logger # @option given_configuration [::Logger::DEBUG, ::Logger::INFO, ::Logger::WARN, ::Logger::ERROR] :log_level # @option given_configuration [Boolean] :raise_errors # @option given_configuration [Boolean] :raise_for_empty_fields # @option given_configuration [::Array<String>] :dynamic_entries # @option given_configuration [::Hash<String, Contentful::Resource>] :resource_mapping # @option given_configuration [::Hash<String, Contentful::Resource>] :entry_mapping # @option given_configuration [String] :application_name # @option given_configuration [String] :application_version # @option given_configuration [String] :integration_name # @option given_configuration [String] :integration_version # @option given_configuration [HTTP::Features::Instrumentation::Instrumenter, nil] :http_instrumenter # An HTTP instrumenter object that implements the instrumentation interface. # When provided, it will be used to instrument all HTTP requests made by the client. # This is useful for monitoring, logging, or tracking HTTP requests. def initialize(given_configuration = {}) @configuration = default_configuration.merge(given_configuration) normalize_configuration! validate_configuration! setup_logger update_dynamic_entry_cache! if configuration[:dynamic_entries] == :auto end # @private def setup_logger @logger = configuration[:logger] logger.level = configuration[:log_level] if logger && configuration.key?(:log_level) end # @private def proxy_params { host: configuration[:proxy_host], port: configuration[:proxy_port], username: configuration[:proxy_username], password: configuration[:proxy_password] } end # @private def timeout_params { connect: configuration[:timeout_connect], read: configuration[:timeout_read], write: configuration[:timeout_write] }.reject { |_, value| value.nil? } end # Returns the default configuration # @private def default_configuration DEFAULT_CONFIGURATION.dup end # Gets the client's space # # @param [Hash] query # # @return [Contentful::Space] def space(query = {}) Request.new(self, '', query).get end # Gets a specific content type # # @param [String] id # @param [Hash] query # # @return [Contentful::ContentType] def content_type(id, query = {}) Request.new(self, environment_url('/content_types'), query, id).get end # Gets a collection of content types # # @param [Hash] query # # @return [Contentful::Array<Contentful::ContentType>] def content_types(query = {}) Request.new(self, environment_url('/content_types'), query).get end # Gets a specific entry # # @param [String] id # @param [Hash] query # # @return [Contentful::Entry] def entry(id, query = {}) normalize_select!(query) query['sys.id'] = id entries = Request.new(self, environment_url('/entries'), query).get return entries if configuration[:raw_mode] entries.first end # Gets a collection of entries # # @param [Hash] query # # @return [Contentful::Array<Contentful::Entry>] def entries(query = {}) normalize_select!(query) Request.new(self, environment_url('/entries'), query).get end # Gets a specific asset # # @param [String] id # @param [Hash] query # # @return [Contentful::Asset] def asset(id, query = {}) Request.new(self, environment_url('/assets'), query, id).get end # Gets a collection of assets # # @param [Hash] query # # @return [Contentful::Array<Contentful::Asset>] def assets(query = {}) normalize_select!(query) Request.new(self, environment_url('/assets'), query).get end # Gets a collection of locales for the current environment # # @param [Hash] query # # @return [Contentful::Array<Contentful::Locale>] def locales(query = {}) Request.new(self, environment_url('/locales'), query).get end # Gets a specific taxonomy concept # # @param [String] id # @param [Hash] query # # @return [Contentful::TaxonomyConcept] def taxonomy_concept(id, query = {}) Request.new(self, environment_url('/taxonomy/concepts'), query, id).get end # Gets a collection of taxonomy concepts # # @param [Hash] query # # @return [Contentful::Array<Contentful::TaxonomyConcept>] def taxonomy_concepts(query = {}) Request.new(self, environment_url('/taxonomy/concepts'), query).get end # Gets a specific taxonomy concept scheme # # @param [String] id # @param [Hash] query # # @return [Contentful::TaxonomyConceptScheme] def taxonomy_concept_scheme(id, query = {}) Request.new(self, environment_url('/taxonomy/concept-schemes'), query, id).get end # Gets a collection of taxonomy concept schemes # # @param [Hash] query # # @return [Contentful::Array<Contentful::TaxonomyConceptScheme>] def taxonomy_concept_schemes(query = {}) Request.new(self, environment_url('/taxonomy/concept-schemes'), query).get end # Returns the base url for all of the client's requests # @private def base_url "http#{configuration[:secure] ? 's' : ''}://#{configuration[:api_url]}/spaces/#{configuration[:space]}" end # Returns the url aware of the currently selected environment # @private def environment_url(path) "/environments/#{configuration[:environment]}#{path}" end # Returns the formatted part of the X-Contentful-User-Agent header # @private def format_user_agent_header(key, values) header = "#{key} #{values[:name]}" header = "#{header}/#{values[:version]}" if values[:version] "#{header};" end # Returns the X-Contentful-User-Agent sdk data # @private def sdk_info { name: 'contentful.rb', version: ::Contentful::VERSION } end # Returns the X-Contentful-User-Agent app data # @private def app_info { name: configuration[:application_name], version: configuration[:application_version] } end # Returns the X-Contentful-User-Agent integration data # @private def integration_info { name: configuration[:integration_name], version: configuration[:integration_version] } end # Returns the X-Contentful-User-Agent platform data # @private def platform_info { name: 'ruby', version: RUBY_VERSION } end # Returns the X-Contentful-User-Agent os data # @private def os_info os_name = case ::RbConfig::CONFIG['host_os'] when /(cygwin|mingw|mswin|windows)/i then 'Windows' when /(darwin|macruby|mac os)/i then 'macOS' when /(linux|bsd|aix|solarix)/i then 'Linux' end { name: os_name, version: Gem::Platform.local.version } end # Returns the X-Contentful-User-Agent # @private def contentful_user_agent header = { 'sdk' => sdk_info, 'app' => app_info, 'integration' => integration_info, 'platform' => platform_info, 'os' => os_info } result = [] header.each do |key, values| next unless values[:name] result << format_user_agent_header(key, values) end result.join(' ') end # Returns the headers used for the HTTP requests # @private def request_headers headers = { 'X-Contentful-User-Agent' => contentful_user_agent } headers['Authorization'] = "Bearer #{configuration[:access_token]}" if configuration[:authentication_mechanism] == :header headers['Content-Type'] = "application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json" if configuration[:api_version] headers['Accept-Encoding'] = 'gzip' if configuration[:gzip_encoded] headers end # Patches a query hash with the client configurations for queries # @private def request_query(query) if configuration[:authentication_mechanism] == :query_string query['access_token'] = configuration[:access_token] end query end # Get a Contentful::Request object # Set second parameter to false to deactivate Resource building and # return Response objects instead # # @private def get(request, build_resource = true) retries_left = configuration[:max_rate_limit_retries] result = nil begin response = run_request(request) return response if !build_resource || configuration[:raw_mode] return fail_response(response) if response.status != :ok result = do_build_resource(response) rescue UnparsableResource => error raise error if configuration[:raise_errors] return error rescue Contentful::RateLimitExceeded => rate_limit_error reset_time = rate_limit_error.reset_time.to_i if should_retry(retries_left, reset_time, configuration[:max_rate_limit_wait]) retries_left -= 1 logger.info(retry_message(retries_left, reset_time)) if logger sleep(reset_time * Random.new.rand(1.0..1.2)) retry end raise end result end # @private def retry_message(retries_left, reset_time) message = 'Contentful API Rate Limit Hit! ' message += "Retrying - Retries left: #{retries_left}" message += "- Time until reset (seconds): #{reset_time}" message end # @private def fail_response(response) fail response.object if configuration[:raise_errors] response.object end # @private def should_retry(retries_left, reset_time, max_wait) retries_left > 0 && max_wait > reset_time end # Runs request and parses Response # @private def run_request(request) url = request.absolute? ? request.url : base_url + request.url logger.info(request: { url: url, query: request.query, header: request_headers }) if logger Response.new( self.class.get_http( url, request_query(request.query), request_headers, proxy_params, timeout_params, configuration[:http_instrumenter] ), request ) end # Runs Resource Builder # @private def do_build_resource(response) logger.debug(response: response) if logger configuration[:resource_builder].new( response.object, configuration.merge(endpoint: response.request.endpoint), (response.request.query || {}).fetch(:locale, nil) == '*', 0, [], response.request.query || {} ).run end # Use this method together with the client's :dynamic_entries configuration. # See README for details. # @private def update_dynamic_entry_cache! return if configuration[:raw_mode] content_types(limit: 1000).map do |ct| ContentTypeCache.cache_set(configuration[:space], ct.id, ct) end end # Use this method to manually register a dynamic entry # See examples/dynamic_entries.rb # @private def register_dynamic_entry(key, klass) ContentTypeCache.cache_set(configuration[:space], key, klass) end # Create a new synchronisation object # # @param [Hash, String] options Options or Sync URL # # @note You will need to call #each_page or #first_page on it # # @return [Contentful::Sync] def sync(options = { initial: true }) Sync.new(self, options) end private # If the query contains the :select operator, we enforce :sys properties. # The SDK requires sys.type to function properly, but as other of our SDKs # require more parts of the :sys properties, we decided that every SDK should # include the complete :sys block to provide consistency accross our SDKs. def normalize_select!(query) return unless query.key?(:select) query[:select] = query[:select].split(',').map(&:strip) if query[:select].is_a? String query[:select] = query[:select].reject { |p| p.start_with?('sys.') } query[:select] << 'sys' unless query[:select].include?('sys') end def normalize_configuration! %i[space access_token api_url default_locale].each { |s| configuration[s] = configuration[s].to_s } configuration[:authentication_mechanism] = configuration[:authentication_mechanism].to_sym end def validate_configuration! fail ArgumentError, 'You will need to initialize a client with a :space' if configuration[:space].empty? fail ArgumentError, 'You will need to initialize a client with an :access_token' if configuration[:access_token].empty? fail ArgumentError, 'The client configuration needs to contain an :api_url' if configuration[:api_url].empty? fail ArgumentError, 'The client configuration needs to contain a :default_locale' if configuration[:default_locale].empty? fail ArgumentError, 'The :api_version must be a positive number or nil' unless configuration[:api_version].to_i >= 0 fail ArgumentError, 'The authentication mechanism must be :header or :query_string' unless %i[header query_string].include?( configuration[:authentication_mechanism] ) fail ArgumentError, 'The :dynamic_entries mode must be :auto or :manual' unless %i[auto manual].include?( configuration[:dynamic_entries] ) fail ArgumentError, 'Timeout parameters must be all omitted or all present' unless timeout_params.empty? || timeout_params.length == 3 end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/request.rb
lib/contentful/request.rb
module Contentful # This object represents a request that is to be made. It gets initialized by the client # with domain specific logic. The client later uses the Request's #url and #query methods # to execute the HTTP request. class Request attr_reader :client, :type, :query, :id, :endpoint def initialize(client, endpoint, query = {}, id = nil) @client = client @endpoint = endpoint @query = (normalize_query(query) if query && !query.empty?) if id @type = :single # Given the deprecation of `URI::escape` and `URI::encode` # it is needed to replace it with `URI::encode_www_form_component`. # This method, does replace spaces with `+` instead of `%20`. # Therefore, to keep backwards compatibility, we're replacing the resulting `+` # back with `%20`. @id = URI.encode_www_form_component(id).gsub('+', '%20') else @type = :multi @id = nil end end # Returns the final URL, relative to a contentful space def url "#{@endpoint}#{@type == :single ? "/#{id}" : ''}" end # Delegates the actual HTTP work to the client def get client.get(self) end # Returns true if endpoint is an absolute url def absolute? @endpoint.start_with?('http') end # Returns a new Request object with the same data def copy Marshal.load(Marshal.dump(self)) end private def normalize_query(query) Hash[ query.map do |key, value| [ key.to_sym, value.is_a?(::Array) ? value.join(',') : value ] end ] end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/includes.rb
lib/contentful/includes.rb
require_relative 'array_like' module Contentful # The includes hashes returned when include_level is specified class Includes include ArrayLike attr_accessor :items, :lookup def initialize(items = [], lookup = nil) self.items = items self.lookup = lookup || build_lookup end def self.from_response(json, raw = true) includes = if raw json['items'].dup else json['items'].map(&:raw) end %w[Entry Asset].each do |type| includes.concat(json['includes'].fetch(type, [])) if json.fetch('includes', {}).key?(type) end new includes || [] end def find_link(link) key = "#{link['sys']['linkType']}:#{link['sys']['id']}" lookup[key] end # Override some of the features of Array to take into account the lookup # field in a performant way. # If the lookups are the same then these two objects are effectively the same def ==(other) object_id == other.object_id || lookup == other.lookup end def +(other) # If we're being asked to add to itself, just return without duplicating return self if self == other dup.tap do |copy| copy.items += other.items copy.lookup.merge!(other.lookup) end end def dup self.class.new(items.dup, lookup.dup) end def marshal_dump items end def marshal_load(array) self.items = array self.lookup = build_lookup end private def build_lookup items.each_with_object({}) do |i, h| key = "#{i['sys']['type']}:#{i['sys']['id']}" h[key] = i end end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/fields_resource.rb
lib/contentful/fields_resource.rb
# frozen_string_literal: true require_relative 'support' require_relative 'base_resource' require_relative 'includes' module Contentful # Base definition of a Contentful Resource containing Field properties class FieldsResource < BaseResource attr_reader :localized # rubocop:disable Metrics/ParameterLists def initialize(item, _configuration, localized = false, includes = Includes.new, entries = {}, depth = 0, errors = []) super @configuration[:errors] = errors @localized = localized @fields = hydrate_fields(includes, entries, errors) define_fields_methods! end # Returns all fields of the asset # # @return [Hash] fields for Resource on selected locale def fields(wanted_locale = nil) wanted_locale = internal_resource_locale if wanted_locale.nil? @fields.fetch(wanted_locale.to_s, {}) end # Returns all fields of the asset with locales nested by field # # @return [Hash] fields for Resource grouped by field name def fields_with_locales remapped_fields = {} locales.each do |locale| fields(locale).each do |name, value| remapped_fields[name] ||= {} remapped_fields[name][locale.to_sym] = value end end remapped_fields end # Provides a list of the available locales for a Resource def locales @fields.keys end # @private def marshal_dump super.merge(raw: raw_with_links, localized: localized) end # @private def marshal_load(raw_object) super(raw_object) @localized = raw_object[:localized] @fields = hydrate_fields( raw_object[:configuration].fetch(:includes_for_single, Includes.new), {}, raw_object[:configuration].fetch(:errors, []) ) define_fields_methods! end # @private def raw_with_links links = fields.keys.select { |property| known_link?(property) } processed_raw = raw.clone processed_raw['fields'] = raw['fields'].clone raw['fields'].each do |k, v| links_key = Support.snakify(k, @configuration[:use_camel_case]) processed_raw['fields'][k] = links.include?(links_key.to_sym) ? send(links_key) : v end processed_raw end private def define_fields_methods! fields.each do |k, v| define_singleton_method(k) { v } unless self.class.method_defined?(k) end end def hydrate_localized_fields(includes, errors, entries) locale = internal_resource_locale result = { locale => {} } raw['fields'].each do |name, locales| locales.each do |loc, value| result[loc] ||= {} name = Support.snakify(name, @configuration[:use_camel_case]) result[loc][name.to_sym] = coerce( name, value, includes, errors, entries ) end end result end def hydrate_nonlocalized_fields(includes, errors, entries) locale = internal_resource_locale result = { locale => {} } raw['fields'].each do |name, value| name = Support.snakify(name, @configuration[:use_camel_case]) result[locale][name.to_sym] = coerce( name, value, includes, errors, entries ) end result end def hydrate_fields(includes, entries, errors) return {} unless raw.key?('fields') if localized hydrate_localized_fields(includes, errors, entries) else hydrate_nonlocalized_fields(includes, errors, entries) end end protected def coerce(_field_id, value, _includes, _errors, _entries) value end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/space.rb
lib/contentful/space.rb
require_relative 'base_resource' require_relative 'locale' module Contentful # Resource class for Space. # https://www.contentful.com/developers/documentation/content-delivery-api/#spaces class Space < BaseResource attr_reader :name, :locales def initialize(item, *) super @name = item.fetch('name', nil) @locales = item.fetch('locales', []).map { |locale| Locale.new(locale) } end # @private def reload(client = nil) return client.space unless client.nil? false end end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false
contentful/contentful.rb
https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/deleted_asset.rb
lib/contentful/deleted_asset.rb
require_relative 'base_resource' module Contentful # Resource class for deleted entries # https://www.contentful.com/developers/documentation/content-delivery-api/http/#sync-item-types class DeletedAsset < BaseResource; end end
ruby
MIT
7e62f9e1accd70f9b5e01892cc42015015a92ee0
2026-01-04T17:44:22.911350Z
false