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
github/markup
https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup/markdown.rb
lib/github/markup/markdown.rb
require "github/markup/implementation" module GitHub module Markup class Markdown < Implementation MARKDOWN_GEMS = { "commonmarker" => proc { |content, options: {}| commonmarker_opts = [:GITHUB_PRE_LANG].concat(options.fetch(:commonmarker_opts, [])) commonmarker_exts = options.fetch(:commonmarker_exts, [:tagfilter, :autolink, :table, :strikethrough]) CommonMarker.render_html(content, commonmarker_opts, commonmarker_exts) }, "github/markdown" => proc { |content, options: {}| GitHub::Markdown.render(content) }, "redcarpet" => proc { |content, options: {}| Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(content) }, "rdiscount" => proc { |content, options: {}| RDiscount.new(content).to_html }, "maruku" => proc { |content, options: {}| Maruku.new(content).to_html }, "kramdown" => proc { |content, options: {}| Kramdown::Document.new(content).to_html }, "bluecloth" => proc { |content, options: {}| BlueCloth.new(content).to_html }, } def initialize super( /md|mkdn?|mdwn|mdown|markdown|mdx|litcoffee/i, ["Markdown", "MDX", "Literate CoffeeScript"]) end def load return if @renderer MARKDOWN_GEMS.each do |gem_name, renderer| if try_require(gem_name) @renderer = renderer return end end raise LoadError, "no suitable markdown gem found" end def render(filename, content, options: {}) load @renderer.call(content, options: options) end def name "markdown" end private def try_require(file) require file true rescue LoadError false end end end end
ruby
MIT
2b0e7f216904253092c90754cd95aac6d499583d
2026-01-04T15:41:08.109033Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/bench.rb
bench.rb
require File.expand_path("../test/helper", __FILE__) require "ffaker" N = 10000 def transaction ActiveRecord::Base.transaction do yield raise ActiveRecord::Rollback end end class Array def rand self[Kernel.rand(length)] end end Book = Class.new ActiveRecord::Base class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class Manual < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :history end class Restaurant < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :finders end BOOKS = [] JOURNALISTS = [] MANUALS = [] RESTAURANTS = [] 100.times do name = FFaker::Name.name BOOKS << (Book.create! name: name).id JOURNALISTS << (Journalist.create! name: name).friendly_id MANUALS << (Manual.create! name: name).friendly_id RESTAURANTS << (Restaurant.create! name: name).friendly_id end ActiveRecord::Base.connection.execute "UPDATE manuals SET slug = NULL" Benchmark.bmbm do |x| x.report "find (without FriendlyId)" do N.times { Book.find BOOKS.rand } end x.report "find (in-table slug)" do N.times { Journalist.friendly.find JOURNALISTS.rand } end x.report "find (in-table slug; using finders module)" do N.times { Restaurant.find RESTAURANTS.rand } end x.report "find (external slug)" do N.times { Manual.friendly.find MANUALS.rand } end x.report "insert (without FriendlyId)" do N.times { transaction { Book.create name: FFaker::Name.name } } end x.report "insert (in-table-slug)" do N.times { transaction { Journalist.create name: FFaker::Name.name } } end x.report "insert (in-table-slug; using finders module)" do N.times { transaction { Restaurant.create name: FFaker::Name.name } } end x.report "insert (external slug)" do N.times { transaction { Manual.create name: FFaker::Name.name } } end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/guide.rb
guide.rb
#!/usr/bin/env ruby # This script generates the Guide.md file included in the Yard docs. def comments_from path path = File.expand_path("../lib/friendly_id/#{path}", __FILE__) matches = File.read(path).match(/\n\s*# @guide begin\n(.*)\s*# @guide end/m) return if matches.nil? match = matches[1].to_s match.split("\n") .map { |x| x.sub(/^\s*#\s?/, "") } # Strip off the comment, leading whitespace, and the space after the comment .reject { |x| x =~ /^@/ } # Ignore yarddoc tags for the guide .join("\n").strip end File.open(File.expand_path("../Guide.md", __FILE__), "w:utf-8") do |guide| ["../friendly_id.rb", "base.rb", "finders.rb", "slugged.rb", "history.rb", "scoped.rb", "simple_i18n.rb", "reserved.rb"].each do |file| guide.write comments_from file guide.write "\n" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-7.2.rb
gemfiles/Gemfile.rails-7.2.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 7.2.0" gem "railties", "~> 7.2.0" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 61.0" gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-6.0.rb
gemfiles/Gemfile.rails-6.0.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 6.0.0" gem "railties", "~> 6.0.0" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 51.1" gem "activerecord-jdbcpostgresql-adapter", "~> 51.1" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-7.1.rb
gemfiles/Gemfile.rails-7.1.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 7.1.0" gem "railties", "~> 7.1.0" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 61.0" gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-7.0.rb
gemfiles/Gemfile.rails-7.0.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 7.0.0" gem "railties", "~> 7.0.0" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 61.0" gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-6.1.rb
gemfiles/Gemfile.rails-6.1.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 6.1.4" gem "railties", "~> 6.1.4" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 61.0" gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/gemfiles/Gemfile.rails-8.0.rb
gemfiles/Gemfile.rails-8.0.rb
source "https://rubygems.org" gemspec path: "../" gem "activerecord", "~> 8.0.0" gem "railties", "~> 8.0.0" # Database Configuration group :development, :test do platforms :jruby do gem "activerecord-jdbcmysql-adapter", "~> 61.0" gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" gem "kramdown" end platforms :ruby, :rbx do gem "sqlite3" gem "mysql2" gem "pg" gem "redcarpet" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/simple_i18n_test.rb
test/simple_i18n_test.rb
require "helper" class SimpleI18nTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :simple_i18n end def setup I18n.locale = :en end test "friendly_id should return the current locale's slug" do journalist = Journalist.new(name: "John Doe") journalist.slug_es = "juan-fulano" journalist.slug_fr_ca = "jean-dupont" journalist.valid? I18n.with_locale(I18n.default_locale) do assert_equal "john-doe", journalist.friendly_id end I18n.with_locale(:es) do assert_equal "juan-fulano", journalist.friendly_id end I18n.with_locale(:"fr-CA") do assert_equal "jean-dupont", journalist.friendly_id end end test "should create record with slug in column for the current locale" do I18n.with_locale(I18n.default_locale) do journalist = Journalist.new(name: "John Doe") journalist.valid? assert_equal "john-doe", journalist.slug_en assert_nil journalist.slug_es end I18n.with_locale(:es) do journalist = Journalist.new(name: "John Doe") journalist.valid? assert_equal "john-doe", journalist.slug_es assert_nil journalist.slug_en end end test "to_param should return the numeric id when there's no slug for the current locale" do transaction do journalist = Journalist.new(name: "Juan Fulano") I18n.with_locale(:es) do journalist.save! assert_equal "juan-fulano", journalist.to_param end assert_equal journalist.id.to_s, journalist.to_param end end test "should set friendly id for locale" do transaction do journalist = Journalist.create!(name: "John Smith") journalist.set_friendly_id("Juan Fulano", :es) journalist.save! assert_equal "juan-fulano", journalist.slug_es I18n.with_locale(:es) do assert_equal "juan-fulano", journalist.to_param end end end test "set friendly_id should fall back default locale when none is given" do transaction do journalist = I18n.with_locale(:es) do Journalist.create!(name: "Juan Fulano") end journalist.set_friendly_id("John Doe") journalist.save! assert_equal "john-doe", journalist.slug_en end end test "should sequence localized slugs" do transaction do journalist = Journalist.create!(name: "John Smith") I18n.with_locale(:es) do Journalist.create!(name: "Juan Fulano") end journalist.set_friendly_id("Juan Fulano", :es) journalist.save! assert_equal "john-smith", journalist.to_param I18n.with_locale(:es) do assert_match(/juan-fulano-.+/, journalist.to_param) end end end class RegressionTest < TestCaseClass include FriendlyId::Test test "should not overwrite other locale's slugs on update" do transaction do journalist = Journalist.create!(name: "John Smith") journalist.set_friendly_id("Juan Fulano", :es) journalist.save! assert_equal "john-smith", journalist.to_param journalist.slug = nil journalist.update name: "Johnny Smith" assert_equal "johnny-smith", journalist.to_param I18n.with_locale(:es) do assert_equal "juan-fulano", journalist.to_param end end end end class ConfigurationTest < TestCaseClass test "should add locale to slug column for a non-default locale" do I18n.with_locale :es do assert_equal "slug_es", Journalist.friendly_id_config.slug_column end end test "should add locale to slug column for a locale with a region subtag" do I18n.with_locale :"fr-CA" do assert_equal "slug_fr_ca", Journalist.friendly_id_config.slug_column end end test "should add locale to non-default slug column and non-default locale" do model_class = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId friendly_id :name, use: :simple_i18n, slug_column: :foo end I18n.with_locale :es do assert_equal "foo_es", model_class.friendly_id_config.slug_column end end test "should add locale to slug column for default locale" do I18n.with_locale(I18n.default_locale) do assert_equal "slug_en", Journalist.friendly_id_config.slug_column end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/sti_test.rb
test/sti_test.rb
require "helper" class StiTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core include FriendlyId::Test::Shared::Slugged class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged] end class Editorialist < Journalist end def model_class Editorialist end test "friendly_id should accept a base and a hash with single table inheritance" do abstract_klass = Class.new(ActiveRecord::Base) do def self.table_exists? false end extend FriendlyId friendly_id :foo, use: :slugged, slug_column: :bar end klass = Class.new(abstract_klass) assert klass < FriendlyId::Slugged assert_equal :foo, klass.friendly_id_config.base assert_equal :bar, klass.friendly_id_config.slug_column end test "the configuration's model_class should be the class, not the base_class" do assert_equal model_class, model_class.friendly_id_config.model_class end test "friendly_id should accept a block with single table inheritance" do abstract_klass = Class.new(ActiveRecord::Base) do def self.table_exists? false end extend FriendlyId friendly_id :foo do |config| config.use :slugged config.base = :foo config.slug_column = :bar end end klass = Class.new(abstract_klass) assert klass < FriendlyId::Slugged assert_equal :foo, klass.friendly_id_config.base assert_equal :bar, klass.friendly_id_config.slug_column end test "friendly_id slugs should not clash with each other" do transaction do journalist = model_class.base_class.create! name: "foo bar" editoralist = model_class.create! name: "foo bar" assert_equal "foo-bar", journalist.slug assert_match(/foo-bar-.+/, editoralist.slug) end end end class StiTestWithHistory < StiTest class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :history] end class Editorialist < Journalist end def model_class Editorialist end end class StiTestWithFinders < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :finders] end class Editorialist < Journalist extend FriendlyId friendly_id :name, use: [:slugged, :finders] end def model_class Editorialist end test "friendly_id slugs should be looked up from subclass with friendly" do transaction do editoralist = model_class.create! name: "foo bar" assert_equal editoralist, model_class.friendly.find(editoralist.slug) end end test "friendly_id slugs should be looked up from subclass" do transaction do editoralist = model_class.create! name: "foo bar" assert_equal editoralist, model_class.find(editoralist.slug) end end end class StiTestSubClass < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId end class Editorialist < Journalist extend FriendlyId friendly_id :name, use: [:slugged, :finders] end def model_class Editorialist end test "friendly_id slugs can be created and looked up from subclass" do transaction do editoralist = model_class.create! name: "foo bar" assert_equal editoralist, model_class.find(editoralist.slug) end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/candidates_test.rb
test/candidates_test.rb
require "helper" class CandidatesTest < TestCaseClass include FriendlyId::Test class Airport def initialize(code) @code = code end attr_reader :code alias_method :to_s, :code end class City < ActiveRecord::Base extend FriendlyId friendly_id :slug_candidates, use: :slugged alias_attribute :slug_candidates, :name end def model_class City end def with_instances_of(klass = model_class, &block) transaction do city1 = klass.create! name: "New York", code: "JFK" city2 = klass.create! name: "New York", code: "EWR" yield city1, city2 end end alias_method :with_instances, :with_instances_of test "resolves conflict with candidate" do with_instances do |city1, city2| assert_equal "new-york", city1.slug assert_match(/\Anew-york-([a-z0-9]+-){4}[a-z0-9]+\z/, city2.slug) end end test "accepts candidate as symbol" do klass = Class.new model_class do def slug_candidates :name end end with_instances_of klass do |_, city| assert_match(/\Anew-york-([a-z0-9]+-){4}[a-z0-9]+\z/, city.slug) end end test "accepts multiple candidates" do klass = Class.new model_class do def slug_candidates [name, code] end end with_instances_of klass do |_, city| assert_equal "ewr", city.slug end end test "ignores blank candidate" do klass = Class.new model_class do def slug_candidates [name, ""] end end with_instances_of klass do |_, city| assert_match(/\Anew-york-([a-z0-9]+-){4}[a-z0-9]+\z/, city.slug) end end test "ignores nil candidate" do klass = Class.new model_class do def slug_candidates [name, nil] end end with_instances_of klass do |_, city| assert_match(/\Anew-york-([a-z0-9]+-){4}[a-z0-9]+\z/, city.slug) end end test "accepts candidate with nested array" do klass = Class.new model_class do def slug_candidates [name, [name, code]] end end with_instances_of klass do |_, city| assert_equal "new-york-ewr", city.slug end end test "accepts candidate with lambda" do klass = Class.new City do def slug_candidates [name, [name, -> { rand 1000 }]] end end with_instances_of klass do |_, city| assert_match(/\Anew-york-\d{,3}\z/, city.friendly_id) end end test "accepts candidate with object" do klass = Class.new City do def slug_candidates [name, [name, Airport.new(code)]] end end with_instances_of klass do |_, city| assert_equal "new-york-ewr", city.friendly_id end end test "allows to iterate through candidates without passing block" do klass = Class.new model_class do def slug_candidates :name end end with_instances_of klass do |_, city| candidates = FriendlyId::Candidates.new(city, city.slug_candidates) assert_equal candidates.each, ["new-york"] end end test "iterates through candidates with passed block" do klass = Class.new model_class do def slug_candidates :name end end with_instances_of klass do |_, city| collected_candidates = [] candidates = FriendlyId::Candidates.new(city, city.slug_candidates) candidates.each { |candidate| collected_candidates << candidate } assert_equal collected_candidates, ["new-york"] end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/generator_test.rb
test/generator_test.rb
require "helper" require "rails/generators" require "generators/friendly_id_generator" class FriendlyIdGeneratorTest < Rails::Generators::TestCase tests FriendlyIdGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "should generate a migration" do run_generator assert_migration "db/migrate/create_friendly_id_slugs" ensure FileUtils.rm_rf destination_root end test "should skip the migration when told to do so" do run_generator ["--skip-migration"] assert_no_migration "db/migrate/create_friendly_id_slugs" ensure FileUtils.rm_rf destination_root end test "should generate an initializer" do run_generator assert_file "config/initializers/friendly_id.rb" ensure FileUtils.rm_rf destination_root end test "should skip the initializer when told to do so" do run_generator ["--skip-initializer"] assert_no_file "config/initializers/friendly_id.rb" ensure FileUtils.rm_rf destination_root end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/history_test.rb
test/history_test.rb
require "helper" class HistoryTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core class Manual < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :history] end def model_class Manual end test "should insert record in slugs table on create" do with_instance_of(model_class) { |record| assert record.slugs.any? } end test "should not create new slug record if friendly_id is not changed" do with_instance_of(model_class) do |record| record.active = true record.save! assert_equal 1, FriendlyId::Slug.count end end test "should create new slug record when friendly_id changes" do with_instance_of(model_class) do |record| record.name = record.name + "b" record.slug = nil record.save! assert_equal 2, FriendlyId::Slug.count end end test "should be findable by old slugs" do with_instance_of(model_class) do |record| old_friendly_id = record.friendly_id record.name = record.name + "b" record.slug = nil record.save! begin assert model_class.friendly.find(old_friendly_id) assert model_class.friendly.exists?(old_friendly_id), "should exist? by old id" rescue ActiveRecord::RecordNotFound flunk "Could not find record by old id" end end end test "should create slug records on each change" do transaction do model_class.create! name: "hello" assert_equal 1, FriendlyId::Slug.count record = model_class.friendly.find("hello") record.name = "hello again" record.slug = nil record.save! assert_equal 2, FriendlyId::Slug.count end end test "should not be read only when found by slug" do with_instance_of(model_class) do |record| refute model_class.friendly.find(record.friendly_id).readonly? assert record.update name: "foo" end end test "should not be read only when found by old slug" do with_instance_of(model_class) do |record| old_friendly_id = record.friendly_id record.name = record.name + "b" record.save! assert !model_class.friendly.find(old_friendly_id).readonly? end end test "should handle renames" do with_instance_of(model_class) do |record| record.name = "x" record.slug = nil assert record.save record.name = "y" record.slug = nil assert record.save record.name = "x" record.slug = nil assert record.save end end test "should maintain history even if current slug is not the most recent one" do with_instance_of(model_class) do |record| record.name = "current" assert record.save # this feels like a hack. only thing i can get to work with the HistoryTestWithSti # test cases. (Editorialist vs Journalist.) sluggable_type = FriendlyId::Slug.first.sluggable_type # create several slugs for record # current slug does not have max id FriendlyId::Slug.delete_all FriendlyId::Slug.create(sluggable_type: sluggable_type, sluggable_id: record.id, slug: "current") FriendlyId::Slug.create(sluggable_type: sluggable_type, sluggable_id: record.id, slug: "outdated") record.reload record.slug = nil assert record.save assert_equal 2, FriendlyId::Slug.count end end test "should not create new slugs that match old slugs" do transaction do first_record = model_class.create! name: "foo" first_record.name = "bar" first_record.save! second_record = model_class.create! name: "foo" assert second_record.slug != "foo" assert_match(/foo-.+/, second_record.slug) end end test "should not fail when updating historic slugs" do transaction do first_record = model_class.create! name: "foo" second_record = model_class.create! name: "another" second_record.update name: "foo", slug: nil assert_match(/foo-.*/, second_record.slug) first_record.update name: "another", slug: nil assert_match(/another-.*/, first_record.slug) end end test "should prefer product that used slug most recently" do transaction do first_record = model_class.create! name: "foo" second_record = model_class.create! name: "bar" first_record.update! slug: "not_foo" second_record.update! slug: "foo" # now both records have used foo; second_record most recently second_record.update! slug: "not_bar" assert_equal model_class.friendly.find("foo"), second_record end end test "should name table according to prefix and suffix" do transaction do prefix = "prefix_" without_prefix = FriendlyId::Slug.table_name ActiveRecord::Base.table_name_prefix = prefix FriendlyId::Slug.reset_table_name assert_equal prefix + without_prefix, FriendlyId::Slug.table_name ensure ActiveRecord::Base.table_name_prefix = "" FriendlyId::Slug.table_name = without_prefix end end end class HistoryTestWithAutomaticSlugRegeneration < HistoryTest class Manual < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :history] def should_generate_new_friendly_id? slug.blank? or name_changed? end end def model_class Manual end test "should allow reversion back to a previously used slug" do with_instance_of(model_class, name: "foo") do |record| record.name = "bar" record.save! assert_equal "bar", record.friendly_id record.name = "foo" record.save! assert_equal "foo", record.friendly_id end end end class DependentDestroyTest < TestCaseClass include FriendlyId::Test class FalseManual < ActiveRecord::Base self.table_name = "manuals" extend FriendlyId friendly_id :name, use: :history, dependent: false end class DefaultManual < ActiveRecord::Base self.table_name = "manuals" extend FriendlyId friendly_id :name, use: :history end test "should allow disabling of dependent destroy" do transaction do assert FriendlyId::Slug.find_by_slug("foo").nil? l = FalseManual.create! name: "foo" assert FriendlyId::Slug.find_by_slug("foo").present? l.destroy assert FriendlyId::Slug.find_by_slug("foo").present? end end test "should dependently destroy by default" do transaction do assert FriendlyId::Slug.find_by_slug("baz").nil? l = DefaultManual.create! name: "baz" assert FriendlyId::Slug.find_by_slug("baz").present? l.destroy assert FriendlyId::Slug.find_by_slug("baz").nil? end end end if ActiveRecord::VERSION::STRING >= "5.0" class HistoryTestWithParanoidDeletes < HistoryTest class ParanoidRecord < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :history, dependent: false default_scope { where(deleted_at: nil) } end def model_class ParanoidRecord end test "slug should have a sluggable even when soft deleted by a library" do transaction do assert FriendlyId::Slug.find_by_slug("paranoid").nil? record = model_class.create(name: "paranoid") assert FriendlyId::Slug.find_by_slug("paranoid").present? record.update deleted_at: Time.now orphan_slug = FriendlyId::Slug.find_by_slug("paranoid") assert orphan_slug.present?, "Orphaned slug should exist" assert orphan_slug.valid?, "Errors: #{orphan_slug.errors.full_messages}" assert orphan_slug.sluggable.present?, "Orphaned slug should still find corresponding paranoid sluggable" end end end end class HistoryTestWithSti < HistoryTest class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :history] end class Editorialist < Journalist end def model_class Editorialist end end class HistoryTestWithFriendlyFinders < HistoryTest class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :finders, :history] end class Restaurant < ActiveRecord::Base extend FriendlyId belongs_to :city friendly_id :name, use: [:slugged, :history, :finders] end test "should be findable by old slugs" do [Journalist, Restaurant].each do |model_class| with_instance_of(model_class) do |record| old_friendly_id = record.friendly_id record.name = record.name + "b" record.slug = nil record.save! begin assert model_class.find(old_friendly_id) assert model_class.exists?(old_friendly_id), "should exist? by old id for #{model_class.name}" rescue ActiveRecord::RecordNotFound flunk "Could not find record by old id for #{model_class.name}" end end end end end class HistoryTestWithFindersBeforeHistory < HistoryTest class Novelist < ActiveRecord::Base has_many :novels end class Novel < ActiveRecord::Base extend FriendlyId belongs_to :novelist friendly_id :name, use: [:finders, :history] def should_generate_new_friendly_id? slug.blank? || name_changed? end end test "should be findable by old slug through has_many association" do transaction do novelist = Novelist.create!(name: "Stephen King") novel = novelist.novels.create(name: "Rita Hayworth and Shawshank Redemption") slug = novel.slug novel.name = "Shawshank Redemption" novel.save! assert_equal novel, Novel.find(slug) assert_equal novel, novelist.novels.find(slug) end end end class City < ActiveRecord::Base has_many :restaurants end class Restaurant < ActiveRecord::Base extend FriendlyId belongs_to :city friendly_id :name, use: [:scoped, :history], scope: :city end class ScopedHistoryTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Restaurant end test "should find old scoped slugs" do transaction do city = City.create! with_instance_of(Restaurant) do |record| record.city = city record.name = "x" record.slug = nil record.save! record.name = "y" record.slug = nil record.save! assert_equal city.restaurants.friendly.find("x"), city.restaurants.friendly.find("y") end end end test "should consider old scoped slugs when creating slugs" do transaction do city = City.create! with_instance_of(Restaurant) do |record| record.city = city record.name = "x" record.slug = nil record.save! record.name = "y" record.slug = nil record.save! second_record = model_class.create! city: city, name: "x" assert_match(/x-.+/, second_record.friendly_id) third_record = model_class.create! city: city, name: "y" assert_match(/y-.+/, third_record.friendly_id) end end end test "should record history when scope changes" do transaction do city1 = City.create! city2 = City.create! with_instance_of(Restaurant) do |record| record.name = "x" record.slug = nil record.city = city1 record.save! assert_equal("city_id:#{city1.id}", record.slugs.reload.first.scope) assert_equal("x", record.slugs.reload.first.slug) record.city = city2 record.save! assert_equal("city_id:#{city2.id}", record.slugs.reload.first.scope) record.name = "y" record.slug = nil record.city = city1 record.save! assert_equal("city_id:#{city1.id}", record.slugs.reload.first.scope) assert_equal("y", record.slugs.reload.first.slug) end end end test "should allow equal slugs in different scopes" do transaction do city = City.create! second_city = City.create! record = model_class.create! city: city, name: "x" second_record = model_class.create! city: second_city, name: "x" assert_equal record.slug, second_record.slug end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/core_test.rb
test/core_test.rb
require "helper" class Book < ActiveRecord::Base extend FriendlyId friendly_id :name end class Author < ActiveRecord::Base extend FriendlyId friendly_id :name has_many :books end class CoreTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Author end test "models don't use friendly_id by default" do assert !Class.new(ActiveRecord::Base) { self.abstract_class = true }.respond_to?(:friendly_id) end test "model classes should have a friendly id config" do assert model_class.friendly_id(:name).friendly_id_config end test "instances should have a friendly id" do with_instance_of(model_class) { |record| assert record.friendly_id } end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/slugged_test.rb
test/slugged_test.rb
require "helper" class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class Article < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class Novelist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, sequence_separator: "_" def normalize_friendly_id(string) super.tr("-", "_") end end class SluggedTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core include FriendlyId::Test::Shared::Slugged def model_class Journalist end test "should allow validations on the slug" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "articles" extend FriendlyId friendly_id :name, use: :slugged validates_length_of :slug, maximum: 1 def self.name "Article" end end instance = model_class.new name: "hello" refute instance.valid? end test "should allow nil slugs" do transaction do m1 = model_class.create! model_class.create! assert_nil m1.slug end end test "should not break validates_uniqueness_of" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "journalists" extend FriendlyId friendly_id :name, use: :slugged validates_uniqueness_of :slug_en def self.name "Journalist" end end transaction do instance = model_class.create! name: "hello", slug_en: "hello" instance2 = model_class.create name: "hello", slug_en: "hello" assert instance.valid? refute instance2.valid? end end test "should allow a record to reuse its own slug" do with_instance_of(model_class) do |record| old_id = record.friendly_id record.slug = nil record.save! assert_equal old_id, record.friendly_id end end test "should not update matching slug" do klass = Class.new model_class do def should_generate_new_friendly_id? name_changed? end end with_instance_of klass do |record| old_id = record.friendly_id record.name += " " record.save! assert_equal old_id, record.friendly_id end end test "should set slug on create if unrelated validations fail" do klass = Class.new model_class do validates_presence_of :active friendly_id :name, use: :slugged def self.name "Journalist" end end transaction do instance = klass.new name: "foo" refute instance.save refute instance.valid? assert_equal "foo", instance.slug end end test "should not set slug on create if slug validation fails" do klass = Class.new model_class do validates_presence_of :active validates_length_of :slug, minimum: 2 friendly_id :name, use: :slugged def self.name "Journalist" end end transaction do instance = klass.new name: "x" refute instance.save refute instance.valid? assert_nil instance.slug end end test "should set slug on create if unrelated validations fail with custom slug_column" do klass = Class.new(ActiveRecord::Base) do self.table_name = "authors" extend FriendlyId validates_presence_of :active friendly_id :name, use: :slugged, slug_column: :subdomain def self.name "Author" end end transaction do instance = klass.new name: "foo" refute instance.save refute instance.valid? assert_equal "foo", instance.subdomain end end test "should not set slug on create if custom slug column validations fail" do klass = Class.new(ActiveRecord::Base) do self.table_name = "authors" extend FriendlyId validates_length_of :subdomain, minimum: 2 friendly_id :name, use: :slugged, slug_column: :subdomain def self.name "Author" end end transaction do instance = klass.new name: "x" refute instance.save refute instance.valid? assert_nil instance.subdomain end end test "should keep new slug on save if unrelated validations fail" do klass = Class.new model_class do validates_presence_of :active friendly_id :name, use: :slugged def self.name "Journalist" end end transaction do instance = klass.new name: "foo", active: true assert instance.save assert instance.valid? instance.name = "foobar" instance.slug = nil instance.active = nil refute instance.save refute instance.valid? assert_equal "foobar", instance.slug end end test "should not update slug on save if slug validations fail" do klass = Class.new model_class do validates_length_of :slug, minimum: 2 friendly_id :name, use: :slugged def self.name "Journalist" end end transaction do instance = klass.new name: "foo", active: true assert instance.save assert instance.valid? instance.name = "x" instance.slug = nil instance.active = nil refute instance.save assert_equal "foo", instance.slug end end end class SlugGeneratorTest < TestCaseClass include FriendlyId::Test def model_class Journalist end test "should quote column names" do model_class = Class.new(ActiveRecord::Base) do # This has been added in 635731bb to fix MySQL/Rubinius. It may still # be necessary, but causes an exception to be raised on Rails 4, so I'm # commenting it out. If it causes MySQL/Rubinius to fail again we'll # look for another solution. # self.abstract_class = true self.table_name = "journalists" extend FriendlyId friendly_id :name, use: :slugged, slug_column: "strange name" end begin with_instance_of(model_class) { |record| assert model_class.friendly.find(record.friendly_id) } rescue ActiveRecord::StatementInvalid flunk "column name was not quoted" end end test "should not resequence lower sequences on update" do transaction do m1 = model_class.create! name: "a b c d" assert_equal "a-b-c-d", m1.slug model_class.create! name: "a b c d" m1 = model_class.friendly.find(m1.id) m1.save! assert_equal "a-b-c-d", m1.slug end end test "should correctly sequence slugs that end with numbers" do transaction do record1 = model_class.create! name: "Peugeot 206" assert_equal "peugeot-206", record1.slug record2 = model_class.create! name: "Peugeot 206" assert_match(/\Apeugeot-206-([a-z0-9]+-){4}[a-z0-9]+\z/, record2.slug) end end test "should correctly sequence slugs with underscores" do transaction do Novelist.create! name: "wordsfail, buildings tumble" record2 = Novelist.create! name: "word fail" assert_equal "word_fail", record2.slug end end test "should correctly sequence numeric slugs" do transaction do n2 = 2.times.map { Article.create name: "123" }.last assert_match(/\A123-.*/, n2.friendly_id) end end end class SlugSeparatorTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, sequence_separator: ":" end def model_class Journalist end test "should sequence with configured sequence separator" do with_instance_of model_class do |record| record2 = model_class.create! name: record.name assert record2.friendly_id.match(/:.*\z/) end end test "should detect when a stored slug has been cleared" do with_instance_of model_class do |record| record.slug = nil assert record.should_generate_new_friendly_id? end end test "should correctly sequence slugs that uses single dashes as sequence separator" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "journalists" extend FriendlyId friendly_id :name, use: :slugged, sequence_separator: "-" def self.name "Journalist" end end transaction do record1 = model_class.create! name: "Peugeot 206" assert_equal "peugeot-206", record1.slug record2 = model_class.create! name: "Peugeot 206" assert_match(/\Apeugeot-206-([a-z0-9]+-){4}[a-z0-9]+\z/, record2.slug) end end test "should sequence blank slugs without a separator" do with_instance_of model_class, name: "" do |record| assert_match(/\A([a-z0-9]+-){4}[a-z0-9]+\z/, record.slug) end end end class SlugLimitTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, slug_limit: 40 end def model_class Journalist end test "should limit slug size" do transaction do m1 = model_class.create! name: "a" * 50 assert_equal m1.slug, "a" * 40 m2 = model_class.create! name: m1.name m2.save! # "aaa-<uid>" assert_match(/\Aa{3}-/, m2.slug) end end end class DefaultScopeTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged default_scope -> { where(active: true).order("id ASC") } end test "friendly_id should correctly sequence a default_scoped ordered table" do transaction do 3.times { assert Journalist.create name: "a", active: true } end end test "friendly_id should correctly sequence a default_scoped scoped table" do transaction do assert Journalist.create name: "a", active: false assert Journalist.create name: "a", active: true end end end class UuidAsPrimaryKeyFindTest < TestCaseClass include FriendlyId::Test class MenuItem < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged before_create :init_primary_key def self.primary_key "uuid_key" end # Overwrite the method added by FriendlyId def self.primary_key_type :uuid end private def init_primary_key self.uuid_key = SecureRandom.uuid end end def model_class MenuItem end test "should have a uuid_key as a primary key" do assert_equal "uuid_key", model_class.primary_key assert_equal :uuid, model_class.primary_key_type end test "should be findable by the UUID primary key" do with_instance_of(model_class) do |record| assert model_class.friendly.find record.id end end test "should handle a string that simply contains a UUID correctly" do with_instance_of(model_class) do |record| assert_raises(ActiveRecord::RecordNotFound) do model_class.friendly.find "test-#{SecureRandom.uuid}" end end end end class UnderscoreAsSequenceSeparatorRegressionTest < TestCaseClass include FriendlyId::Test class Manual < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, sequence_separator: "_" end test "should not create duplicate slugs" do 3.times do transaction do assert Manual.create! name: "foo" rescue flunk "Tried to insert duplicate slug" end end end end # https://github.com/norman/friendly_id/issues/148 class FailedValidationAfterUpdateRegressionTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged validates_presence_of :slug_de end test "to_param should return the unchanged value if the slug changes before validation fails" do transaction do journalist = Journalist.create! name: "Joseph Pulitzer", slug_de: "value" assert_equal "joseph-pulitzer", journalist.to_param assert journalist.valid? assert journalist.persisted? journalist.name = "Joe Pulitzer" journalist.slug_de = nil assert !journalist.valid? assert_equal "joseph-pulitzer", journalist.to_param end end end # https://github.com/norman/friendly_id/issues/947 class GeneratingSlugWithValidationSkippedTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end test "should generate slug when skipping validation" do transaction do m1 = Journalist.new m1.name = "Bob Timesletter" m1.save(validate: false) assert_equal "bob-timesletter", m1.slug end end test "should generate slug when #valid? called" do transaction do m1 = Journalist.new m1.name = "Bob Timesletter" m1.valid? m1.save(validate: false) assert_equal "bob-timesletter", m1.slug end end end class ToParamTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId validates_presence_of :active validates_length_of :slug, minimum: 2 friendly_id :name, use: :slugged attr_accessor :to_param_in_callback after_save do self.to_param_in_callback = to_param end end test "to_param should return nil if record is unpersisted" do assert_nil Journalist.new.to_param end test "to_param should return original slug if record failed validation" do journalist = Journalist.new name: "Clark Kent", active: nil refute journalist.save assert_equal "clark-kent", journalist.to_param end test "to_param should clear slug attributes if slug attribute fails validation" do journalist = Journalist.new name: "x", active: true refute journalist.save assert_nil journalist.to_param end test "to_param should clear slug attribute if slug attribute fails validation and unrelated validation fails" do journalist = Journalist.new name: "x", active: nil refute journalist.save assert_nil journalist.to_param end test "to_param should use slugged attribute if record saved successfully" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save assert_equal "clark-kent", journalist.to_param end end test "to_param should use new slug if existing record changes but fails to save" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save journalist.name = "Superman" journalist.slug = nil journalist.active = nil refute journalist.save assert_equal "superman", journalist.to_param end end test "to_param should use original slug if new slug attribute is not valid" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save journalist.name = "x" journalist.slug = nil journalist.active = nil refute journalist.save assert_equal "clark-kent", journalist.to_param end end test "to_param should use new slug if existing record changes successfully" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save journalist.name = "Superman" journalist.slug = nil assert journalist.save assert_equal "superman", journalist.to_param end end test "to_param should use new slug within callbacks if new record is saved successfully" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save assert_equal "clark-kent", journalist.to_param_in_callback, "value of to_param in callback should use the new slug value" end end test "to_param should use new slug within callbacks if existing record changes successfully" do transaction do journalist = Journalist.new name: "Clark Kent", active: true assert journalist.save assert journalist.valid? journalist.name = "Superman" journalist.slug = nil assert journalist.save, "save should be successful" assert_equal "superman", journalist.to_param_in_callback, "value of to_param in callback should use the new slug value" end end end class ConfigurableRoutesTest < TestCaseClass include FriendlyId::Test class Article < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, routes: :friendly end class Novel < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged, routes: :default end test "to_param should return a friendly id when the routes option is set to :friendly" do transaction do article = Article.create! name: "Titanic Hits; Iceberg Sinks" assert_equal "titanic-hits-iceberg-sinks", article.to_param end end test "to_param should return the id when the routes option is set to anything but friendly" do transaction do novel = Novel.create! name: "Don Quixote" assert_equal novel.id.to_s, novel.to_param end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/object_utils_test.rb
test/object_utils_test.rb
require "helper" class ObjectUtilsTest < TestCaseClass include FriendlyId::Test test "strings with letters are friendly_ids" do assert "a".friendly_id? end test "integers should be unfriendly ids" do assert 1.unfriendly_id? end test "numeric strings are neither friendly nor unfriendly" do assert_nil "1".friendly_id? assert_nil "1".unfriendly_id? end test "ActiveRecord::Base instances should be unfriendly_ids" do FriendlyId.mark_as_unfriendly(ActiveRecord::Base) model_class = Class.new(ActiveRecord::Base) do self.table_name = "authors" end assert model_class.new.unfriendly_id? end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/sequentially_slugged_test.rb
test/sequentially_slugged_test.rb
require "helper" class Article < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :sequentially_slugged end class SequentiallySluggedTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Article end test "should generate numerically sequential slugs" do transaction do records = 12.times.map { model_class.create! name: "Some news" } assert_equal "some-news", records[0].slug (1...12).each { |i| assert_equal "some-news-#{i + 1}", records[i].slug } end end test "should cope when slugs are missing from the sequence" do transaction do record_1 = model_class.create!(name: "A thing") record_2 = model_class.create!(name: "A thing") record_3 = model_class.create!(name: "A thing") assert_equal "a-thing", record_1.slug assert_equal "a-thing-2", record_2.slug assert_equal "a-thing-3", record_3.slug record_2.destroy record_4 = model_class.create!(name: "A thing") assert_equal "a-thing-4", record_4.slug end end test "should cope with strange column names" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "journalists" extend FriendlyId friendly_id :name, use: :sequentially_slugged, slug_column: "strange name" end transaction do record_1 = model_class.create! name: "Lois Lane" record_2 = model_class.create! name: "Lois Lane" assert_equal "lois-lane", record_1.attributes["strange name"] assert_equal "lois-lane-2", record_2.attributes["strange name"] end end test "should correctly sequence slugs that end in a number" do transaction do record1 = model_class.create! name: "Peugeuot 206" assert_equal "peugeuot-206", record1.slug record2 = model_class.create! name: "Peugeuot 206" assert_equal "peugeuot-206-2", record2.slug end end test "should correctly sequence slugs that begin with a number" do transaction do record1 = model_class.create! name: "2010 to 2015 Records" assert_equal "2010-to-2015-records", record1.slug record2 = model_class.create! name: "2010 to 2015 Records" assert_equal "2010-to-2015-records-2", record2.slug end end test "should sequence with a custom sequence separator" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "novelists" extend FriendlyId friendly_id :name, use: :sequentially_slugged, sequence_separator: ":" end transaction do record_1 = model_class.create! name: "Julian Barnes" record_2 = model_class.create! name: "Julian Barnes" assert_equal "julian-barnes", record_1.slug assert_equal "julian-barnes:2", record_2.slug end end test "should not generate a slug when canidates set is empty" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "cities" extend FriendlyId friendly_id :slug_candidates, use: [:sequentially_slugged] def slug_candidates [name, [name, code]] end end transaction do record = model_class.create!(name: nil, code: nil) assert_nil record.slug end end test "should not generate a slug when the sluggable attribute is blank" do record = model_class.create!(name: "") assert_nil record.slug end end class SequentiallySluggedTestWithHistory < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core class Article < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:sequentially_slugged, :history] end Journalist = Class.new(ActiveRecord::Base) do extend FriendlyId friendly_id :name, use: [:sequentially_slugged, :history], slug_column: "strange name" end def model_class Article end test "should work with regeneration with history when slug already exists" do transaction do record1 = model_class.create! name: "Test name" record2 = model_class.create! name: "Another test name" assert_equal "test-name", record1.slug assert_equal "another-test-name", record2.slug record2.name = "Test name" record2.slug = nil record2.save! assert_equal "test-name-2", record2.slug end end test "should work with regeneration with history when 2 slugs already exists and the second is changed" do transaction do record1 = model_class.create! name: "Test name" record2 = model_class.create! name: "Test name" record3 = model_class.create! name: "Another test name" assert_equal "test-name", record1.slug assert_equal "test-name-2", record2.slug assert_equal "another-test-name", record3.slug record2.name = "One more test name" record2.slug = nil record2.save! assert_equal "one-more-test-name", record2.slug record3.name = "Test name" record3.slug = nil record3.save! assert_equal "test-name-3", record3.slug end end test "should cope with strange column names" do transaction do record_1 = Journalist.create! name: "Lois Lane" record_2 = Journalist.create! name: "Lois Lane" assert_equal "lois-lane", record_1.attributes["strange name"] assert_equal "lois-lane-2", record_2.attributes["strange name"] end end end class City < ActiveRecord::Base has_many :restaurants end class Restaurant < ActiveRecord::Base extend FriendlyId belongs_to :city friendly_id :name, use: [:sequentially_slugged, :scoped, :history], scope: :city end class SequentiallySluggedTestWithScopedHistory < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Restaurant end test "should work with regeneration with scoped history" do transaction do city1 = City.create! City.create! record1 = model_class.create! name: "Test name", city: city1 record2 = model_class.create! name: "Test name", city: city1 assert_equal "test-name", record1.slug assert_equal "test-name-2", record2.slug record2.name = "Another test name" record2.slug = nil record2.save! record3 = model_class.create! name: "Test name", city: city1 assert_equal "test-name-3", record3.slug end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/finders_test.rb
test/finders_test.rb
require "helper" class JournalistWithFriendlyFinders < ActiveRecord::Base self.table_name = "journalists" extend FriendlyId scope :existing, -> { where("1 = 1") } friendly_id :name, use: [:slugged, :finders] end class Finders < TestCaseClass include FriendlyId::Test def model_class JournalistWithFriendlyFinders end test "should find records with finders as class methods" do with_instance_of(model_class) do |record| assert model_class.find(record.friendly_id) end end test "should find records with finders on relations" do with_instance_of(model_class) do |record| assert model_class.existing.find(record.friendly_id) end end test "allows nil with allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.find("foo", allow_nil: true) end end test "allows nil on relations with allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.existing.find("foo", allow_nil: true) end end test "allows nil with a bad primary key ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.find(0, allow_nil: true) end end test "allows nil on relations with a bad primary key ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.existing.find(0, allow_nil: true) end end test "allows nil with a bad potential primary key ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.find("0", allow_nil: true) end end test "allows nil on relations with a bad potential primary key ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.existing.find("0", allow_nil: true) end end test "allows nil with nil ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.find(nil, allow_nil: true) end end test "allows nil on relations with nil ID and allow_nil: true" do with_instance_of(model_class) do |record| assert_nil model_class.existing.find(nil, allow_nil: true) end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/numeric_slug_test.rb
test/numeric_slug_test.rb
require "helper" class Article < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class ArticleWithNumericPrevention < ActiveRecord::Base self.table_name = "articles" extend FriendlyId friendly_id :name, use: :slugged friendly_id_config.treat_numeric_as_conflict = true end class NumericSlugTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Article end test "should generate numeric slugs" do transaction do record = model_class.create! name: "123" assert_equal "123", record.slug end end test "should find by numeric slug" do transaction do record = model_class.create! name: "123" assert_equal model_class.friendly.find("123").id, record.id end end test "should exist? by numeric slug" do transaction do model_class.create! name: "123" assert model_class.friendly.exists?("123") end end test "should prevent purely numeric slugs when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "123" refute_equal "123", record.slug assert_match(/\A123-[0-9a-f-]{36}\z/, record.slug) end end test "should allow non-numeric slugs when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "abc123" assert_equal "abc123", record.slug end end test "should allow alphanumeric slugs when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "product-123" assert_equal "product-123", record.slug end end test "should handle zero as numeric when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "0" refute_equal "0", record.slug assert_match(/\A0-[0-9a-f-]{36}\z/, record.slug) end end test "should handle large numbers as numeric when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "999999999" refute_equal "999999999", record.slug assert_match(/\A999999999-[0-9a-f-]{36}\z/, record.slug) end end test "should find records with UUID-suffixed numeric slugs when treat_numeric_as_conflict is enabled" do transaction do record = ArticleWithNumericPrevention.create! name: "123" found = ArticleWithNumericPrevention.friendly.find(record.slug) assert_equal record.id, found.id end end test "should resolve conflicts between multiple numeric slugs when treat_numeric_as_conflict is enabled" do transaction do record1 = ArticleWithNumericPrevention.create! name: "456" record2 = ArticleWithNumericPrevention.create! name: "456" refute_equal record1.slug, record2.slug assert_match(/\A456-[0-9a-f-]{36}\z/, record1.slug) assert_match(/\A456-[0-9a-f-]{36}\z/, record2.slug) end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/configuration_test.rb
test/configuration_test.rb
require "helper" class ConfigurationTest < TestCaseClass include FriendlyId::Test def setup @model_class = Class.new(ActiveRecord::Base) do self.abstract_class = true end end test "should set model class on initialization" do config = FriendlyId::Configuration.new @model_class assert_equal @model_class, config.model_class end test "should set options on initialization if present" do config = FriendlyId::Configuration.new @model_class, base: "hello" assert_equal "hello", config.base end test "should raise error if passed unrecognized option" do assert_raises NoMethodError do FriendlyId::Configuration.new @model_class, foo: "bar" end end test "#use should accept a name that resolves to a module" do refute @model_class < FriendlyId::Slugged @model_class.class_eval do extend FriendlyId friendly_id :hello, use: :slugged end assert @model_class < FriendlyId::Slugged end test "#use should accept a module" do my_module = Module.new refute @model_class < my_module @model_class.class_eval do extend FriendlyId friendly_id :hello, use: my_module end assert @model_class < my_module end test "#base should optionally set a value" do config = FriendlyId::Configuration.new @model_class assert_nil config.base config.base = "foo" assert_equal "foo", config.base end test "#base can set the value to nil" do config = FriendlyId::Configuration.new @model_class config.base "foo" config.base nil assert_nil config.base end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/helper.rb
test/helper.rb
require "bundler/setup" if ENV["COVERALLS"] || ENV["COVERAGE"] require "simplecov" if ENV["COVERALLS"] require "coveralls" SimpleCov.formatter = Coveralls::SimpleCov::Formatter end SimpleCov.start do add_filter "test" add_filter "friendly_id/migration" end end begin require "minitest" rescue LoadError require "minitest/unit" end begin TestCaseClass = Minitest::Test rescue NameError TestCaseClass = Minitest::Unit::TestCase end require "mocha/minitest" require "active_record" require "active_support/core_ext/time/conversions" require "erb" I18n.enforce_available_locales = false require "friendly_id" # If you want to see the ActiveRecord log, invoke the tests using `rake test LOG=true` if ENV["LOG"] require "logger" ActiveRecord::Base.logger = Logger.new($stdout) end if ActiveSupport::VERSION::STRING >= "4.2" ActiveSupport.test_order = :random end module FriendlyId module Test def self.included(base) if Minitest.respond_to?(:autorun) Minitest.autorun else require "minitest/autorun" end rescue LoadError end def transaction ActiveRecord::Base.transaction do yield raise ActiveRecord::Rollback end end def with_instance_of(*args) model_class = args.shift args[0] ||= {name: "a b c"} transaction { yield model_class.create!(*args) } end module Database extend self def connect version = ActiveRecord::VERSION::STRING engine = begin RUBY_ENGINE rescue "ruby" end ActiveRecord::Base.establish_connection config[driver] message = "Using #{engine} #{RUBY_VERSION} AR #{version} with #{driver}" puts "-" * 72 if in_memory? ActiveRecord::Migration.verbose = false Schema.migrate :up puts "#{message} (in-memory)" else puts message end end def config @config ||= YAML.safe_load( ERB.new( File.read(File.expand_path("../databases.yml", __FILE__)) ).result ) end def driver db_driver = ENV.fetch("DB", "sqlite3").downcase db_driver = "postgres" if %w[postgresql pg].include?(db_driver) db_driver end def in_memory? config[driver]["database"] == ":memory:" end end end end class Module def test(name, &block) define_method("test_#{name.gsub(/[^a-z0-9']/i, "_")}".to_sym, &block) end end require "schema" require "shared" FriendlyId::Test::Database.connect at_exit { ActiveRecord::Base.connection.disconnect! }
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/base_test.rb
test/base_test.rb
require "helper" class CoreTest < TestCaseClass include FriendlyId::Test test "friendly_id can be added using 'extend'" do klass = Class.new(ActiveRecord::Base) do extend FriendlyId end assert klass.respond_to? :friendly_id end test "friendly_id can be added using 'include'" do klass = Class.new(ActiveRecord::Base) do include FriendlyId end assert klass.respond_to? :friendly_id end test "friendly_id should accept a base and a hash" do klass = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId friendly_id :foo, use: :slugged, slug_column: :bar end assert klass < FriendlyId::Slugged assert_equal :foo, klass.friendly_id_config.base assert_equal :bar, klass.friendly_id_config.slug_column end test "friendly_id should accept a block" do klass = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId friendly_id :foo do |config| config.use :slugged config.base = :foo config.slug_column = :bar end end assert klass < FriendlyId::Slugged assert_equal :foo, klass.friendly_id_config.base assert_equal :bar, klass.friendly_id_config.slug_column end test "the block passed to friendly_id should be evaluated before arguments" do klass = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId friendly_id :foo do |config| config.base = :bar end end assert_equal :foo, klass.friendly_id_config.base end test "should allow defaults to be set via a block" do FriendlyId.defaults do |config| config.base = :foo end klass = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId end assert_equal :foo, klass.friendly_id_config.base ensure FriendlyId.instance_variable_set :@defaults, nil end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/reserved_test.rb
test/reserved_test.rb
require "helper" class ReservedTest < TestCaseClass include FriendlyId::Test class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :slug_candidates, use: [:slugged, :reserved], reserved_words: %w[new edit] after_validation :move_friendly_id_error_to_name def move_friendly_id_error_to_name errors.add :name, *errors.delete(:friendly_id) if errors[:friendly_id].present? end def slug_candidates name end end def model_class Journalist end test "should reserve words" do %w[new edit NEW Edit].each do |word| transaction do assert_raises(ActiveRecord::RecordInvalid) { model_class.create! name: word } end end end test "should move friendly_id error to name" do with_instance_of(model_class) do |record| record.errors.add :name, "xxx" record.errors.add :friendly_id, "yyy" record.move_friendly_id_error_to_name assert record.errors[:name].present? && record.errors[:friendly_id].blank? assert_equal 2, record.errors.count end end test "should reject reserved candidates" do transaction do record = model_class.new(name: "new") def record.slug_candidates [:name, "foo"] end record.save! assert_equal "foo", record.friendly_id end end test "should be invalid if all candidates are reserved" do transaction do record = model_class.new(name: "new") def record.slug_candidates ["edit", "new"] end assert_raises(ActiveRecord::RecordInvalid) { record.save! } end end test "should optionally treat reserved words as conflict" do klass = Class.new(model_class) do friendly_id :slug_candidates, use: [:slugged, :reserved], reserved_words: %w[new edit], treat_reserved_as_conflict: true end with_instance_of(klass, name: "new") do |record| assert_match(/new-([0-9a-z]+-){4}[0-9a-z]+\z/, record.slug) end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/schema.rb
test/schema.rb
require "friendly_id/migration" module FriendlyId module Test migration_class = if ActiveRecord::VERSION::MAJOR >= 5 ActiveRecord::Migration[4.2] else ActiveRecord::Migration end class Schema < migration_class class << self def down CreateFriendlyIdSlugs.down tables.each do |name| drop_table name end end def up # TODO: use schema version to avoid ugly hacks like this return if @done CreateFriendlyIdSlugs.migrate :up tables.each do |table_name| create_table table_name do |t| t.string :name t.boolean :active end end tables_with_uuid_primary_key.each do |table_name| create_table table_name, primary_key: :uuid_key, id: false do |t| t.string :name t.string :uuid_key, null: false t.string :slug end add_index table_name, :slug, unique: true end slugged_tables.each do |table_name| add_column table_name, :slug, :string add_index table_name, :slug, unique: true if table_name != "novels" end scoped_tables.each do |table_name| add_column table_name, :slug, :string end paranoid_tables.each do |table_name| add_column table_name, :slug, :string add_column table_name, :deleted_at, :datetime add_index table_name, :deleted_at end # This will be used to test scopes add_column :novels, :novelist_id, :integer add_column :novels, :publisher_id, :integer add_index :novels, [:slug, :publisher_id, :novelist_id], unique: true # This will be used to test column name quoting add_column :journalists, "strange name", :string # This will be used to test STI add_column :journalists, "type", :string # These will be used to test i18n add_column :journalists, "slug_en", :string add_column :journalists, "slug_es", :string add_column :journalists, "slug_de", :string add_column :journalists, "slug_fr_ca", :string # This will be used to test relationships add_column :books, :author_id, :integer # Used to test :scoped and :history together add_column :restaurants, :city_id, :integer # Used to test candidates add_column :cities, :code, :string, limit: 3 # Used as a non-default slug_column add_column :authors, :subdomain, :string @done = true end private def slugged_tables %w[journalists articles novelists novels manuals cities] end def paranoid_tables ["paranoid_records"] end def tables_with_uuid_primary_key ["menu_items"] end def scoped_tables ["restaurants"] end def simple_tables %w[authors books publishers] end def tables simple_tables + slugged_tables + scoped_tables + paranoid_tables end end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/shared.rb
test/shared.rb
module FriendlyId module Test module Shared module Slugged test "configuration should have a sequence_separator" do assert !model_class.friendly_id_config.sequence_separator.empty? end test "should make a new slug if the slug has been set to nil changed" do with_instance_of model_class do |record| record.name = "Changed Value" record.slug = nil record.save! assert_equal "changed-value", record.slug end end test "should add a UUID for duplicate friendly ids" do with_instance_of model_class do |record| record2 = model_class.create! name: record.name assert record2.friendly_id.match(/([0-9a-z]+-){4}[0-9a-z]+\z/) end end test "should not add slug sequence on update after other conflicting slugs were added" do with_instance_of model_class do |record| old = record.friendly_id model_class.create! name: record.name record.save! record.reload assert_equal old, record.to_param end end test "should not change the sequence on save" do with_instance_of model_class do |record| record2 = model_class.create! name: record.name friendly_id = record2.friendly_id record2.active = !record2.active record2.save! assert_equal friendly_id, record2.reload.friendly_id end end test "should create slug on save if the slug is nil" do with_instance_of model_class do |record| record.slug = nil record.save! refute_nil record.slug end end test "should set the slug to nil on dup" do with_instance_of model_class do |record| record2 = record.dup assert_nil record2.slug end end test "when validations block save, to_param should return friendly_id rather than nil" do my_model_class = Class.new(model_class) self.class.const_set("Foo", my_model_class) with_instance_of my_model_class do |record| record.update my_model_class.friendly_id_config.slug_column => nil record = my_model_class.friendly.find(record.id) record.class.validate proc { errors.add(:name, "FAIL") } record.save assert_equal record.to_param, record.friendly_id end end end module Core test "finds should respect conditions" do with_instance_of(model_class) do |record| assert_raises(ActiveRecord::RecordNotFound) do model_class.where("1 = 2").friendly.find record.friendly_id end assert_raises(ActiveRecord::RecordNotFound) do model_class.where("1 = 2").friendly.find record.id end end end test "should be findable by friendly id" do with_instance_of(model_class) { |record| assert model_class.friendly.find record.friendly_id } end test "should exist? by friendly id" do with_instance_of(model_class) do |record| assert model_class.friendly.exists? record.id assert model_class.friendly.exists? record.id.to_s assert model_class.friendly.exists? record.friendly_id assert model_class.friendly.exists?({id: record.id}) assert model_class.friendly.exists?(["id = ?", record.id]) assert !model_class.friendly.exists?(record.friendly_id + "-hello") assert !model_class.friendly.exists?(0) end end test "should be findable by id as integer" do with_instance_of(model_class) { |record| assert model_class.friendly.find record.id.to_i } end test "should be findable by id as string" do with_instance_of(model_class) { |record| assert model_class.friendly.find record.id.to_s } end test "should treat numeric part of string as an integer id" do with_instance_of(model_class) do |record| assert_raises(ActiveRecord::RecordNotFound) do model_class.friendly.find "#{record.id}-foo" end end end test "should be findable by numeric friendly_id" do with_instance_of(model_class, name: "206") { |record| assert model_class.friendly.find record.friendly_id } end test "to_param should return the friendly_id" do with_instance_of(model_class) { |record| assert_equal record.friendly_id, record.to_param } end if ActiveRecord::VERSION::MAJOR == 4 && ActiveRecord::VERSION::MINOR < 2 test "should be findable by themselves" do with_instance_of(model_class) { |record| assert_equal record, model_class.friendly.find(record) } end end test "updating record's other values should not change the friendly_id" do with_instance_of model_class do |record| old = record.friendly_id record.update! active: false assert model_class.friendly.find old end end test "instances found by a single id should not be read-only" do with_instance_of(model_class) { |record| assert !model_class.friendly.find(record.friendly_id).readonly? } end test "failing finds with unfriendly_id should raise errors normally" do assert_raises(ActiveRecord::RecordNotFound) { model_class.friendly.find 0 } end test "should return numeric id if the friendly_id is nil" do with_instance_of(model_class) do |record| record.expects(:friendly_id).returns(nil) assert_equal record.id.to_s, record.to_param end end test "should return numeric id if the friendly_id is an empty string" do with_instance_of(model_class) do |record| record.expects(:friendly_id).returns("") assert_equal record.id.to_s, record.to_param end end test "should return the friendly_id as a string" do with_instance_of(model_class) do |record| record.expects(:friendly_id).returns(5) assert_equal "5", record.to_param end end test "should return numeric id if the friendly_id is blank" do with_instance_of(model_class) do |record| record.expects(:friendly_id).returns(" ") assert_equal record.id.to_s, record.to_param end end test "should return nil for to_param with a new record" do assert_nil model_class.new.to_param end end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/scoped_test.rb
test/scoped_test.rb
require "helper" class Novelist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class Novel < ActiveRecord::Base extend FriendlyId belongs_to :novelist belongs_to :publisher friendly_id :name, use: :scoped, scope: [:publisher, :novelist] def should_generate_new_friendly_id? new_record? || super end end class Publisher < ActiveRecord::Base has_many :novels end class ScopedTest < TestCaseClass include FriendlyId::Test include FriendlyId::Test::Shared::Core def model_class Novel end test "should detect scope column from belongs_to relation" do assert_equal ["publisher_id", "novelist_id"], Novel.friendly_id_config.scope_columns end test "should detect scope column from explicit column name" do model_class = Class.new(ActiveRecord::Base) do self.abstract_class = true extend FriendlyId friendly_id :empty, use: :scoped, scope: :dummy end assert_equal ["dummy"], model_class.friendly_id_config.scope_columns end test "should allow duplicate slugs outside scope" do transaction do novel1 = Novel.create! name: "a", novelist: Novelist.create!(name: "a") novel2 = Novel.create! name: "a", novelist: Novelist.create!(name: "b") assert_equal novel1.friendly_id, novel2.friendly_id end end test "should not allow duplicate slugs inside scope" do with_instance_of Novelist do |novelist| novel1 = Novel.create! name: "a", novelist: novelist novel2 = Novel.create! name: "a", novelist: novelist assert novel1.friendly_id != novel2.friendly_id end end test "should apply scope with multiple columns" do transaction do novelist = Novelist.create! name: "a" publisher = Publisher.create! name: "b" novel1 = Novel.create! name: "c", novelist: novelist, publisher: publisher novel2 = Novel.create! name: "c", novelist: novelist, publisher: Publisher.create(name: "d") novel3 = Novel.create! name: "c", novelist: Novelist.create(name: "e"), publisher: publisher novel4 = Novel.create! name: "c", novelist: novelist, publisher: publisher assert_equal novel1.friendly_id, novel2.friendly_id assert_equal novel2.friendly_id, novel3.friendly_id assert novel3.friendly_id != novel4.friendly_id end end test "should allow a record to reuse its own slug" do with_instance_of(model_class) do |record| old_id = record.friendly_id record.slug = nil record.save! assert_equal old_id, record.friendly_id end end test "should generate new slug when scope changes" do transaction do novelist = Novelist.create! name: "a" publisher = Publisher.create! name: "b" novel1 = Novel.create! name: "c", novelist: novelist, publisher: publisher novel2 = Novel.create! name: "c", novelist: novelist, publisher: Publisher.create(name: "d") assert_equal novel1.friendly_id, novel2.friendly_id novel2.publisher = publisher novel2.save! assert novel2.friendly_id != novel1.friendly_id end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/benchmarks/finders.rb
test/benchmarks/finders.rb
require File.expand_path("../../helper", __FILE__) require "ffaker" # This benchmark tests ActiveRecord and FriendlyId methods for performing a find # # ActiveRecord: where.first 8.970000 0.040000 9.010000 ( 9.029544) # ActiveRecord: where.take 8.100000 0.030000 8.130000 ( 8.157024) # ActiveRecord: find 2.720000 0.010000 2.730000 ( 2.733527) # ActiveRecord: find_by(:id) 2.920000 0.000000 2.920000 ( 2.926318) # ActiveRecord: find_by(:slug) 2.650000 0.020000 2.670000 ( 2.662677) # FriendlyId: find (in-table slug w/ finders) 9.820000 0.030000 9.850000 ( 9.873358) # FriendlyId: friendly.find (in-table slug) 12.890000 0.050000 12.940000 ( 12.951156) N = 50000 def transaction ActiveRecord::Base.transaction do yield raise ActiveRecord::Rollback end end class Array def rand self[Kernel.rand(length)] end end Book = Class.new ActiveRecord::Base class Journalist < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged end class Manual < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :history end class Restaurant < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :finders end BOOKS = [] JOURNALISTS = [] MANUALS = [] RESTAURANTS = [] 100.times do name = FFaker::Name.name BOOKS << (Book.create! name: name).id JOURNALISTS << (Journalist.create! name: name).friendly_id MANUALS << (Manual.create! name: name).friendly_id RESTAURANTS << (Restaurant.create! name: name).friendly_id end ActiveRecord::Base.connection.execute "UPDATE manuals SET slug = NULL" Benchmark.bmbm do |x| x.report "ActiveRecord: where.first" do N.times { Book.where(id: BOOKS.rand).first } end x.report "ActiveRecord: where.take" do N.times { Book.where(id: BOOKS.rand).take } end x.report "ActiveRecord: find" do N.times { Book.find BOOKS.rand } end x.report "ActiveRecord: find_by(:id)" do N.times { Book.find_by(id: BOOKS.rand) } end x.report "ActiveRecord: find_by(:slug)" do N.times { Restaurant.find_by(slug: RESTAURANTS.rand) } end x.report "FriendlyId: find (in-table slug w/ finders)" do N.times { Restaurant.find RESTAURANTS.rand } end x.report "FriendlyId: friendly.find (in-table slug)" do N.times { Restaurant.friendly.find RESTAURANTS.rand } end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/test/benchmarks/object_utils.rb
test/benchmarks/object_utils.rb
require File.expand_path("../../helper", __FILE__) # This benchmark compares the timings of the friendly_id? and unfriendly_id? on various objects # # integer friendly_id? 6.370000 0.000000 6.370000 ( 6.380925) # integer unfriendly_id? 6.640000 0.010000 6.650000 ( 6.646057) # AR::Base friendly_id? 2.340000 0.000000 2.340000 ( 2.340743) # AR::Base unfriendly_id? 2.560000 0.000000 2.560000 ( 2.560039) # hash friendly_id? 5.090000 0.010000 5.100000 ( 5.097662) # hash unfriendly_id? 5.430000 0.000000 5.430000 ( 5.437160) # nil friendly_id? 5.610000 0.010000 5.620000 ( 5.611487) # nil unfriendly_id? 5.870000 0.000000 5.870000 ( 5.880484) # numeric string friendly_id? 9.270000 0.030000 9.300000 ( 9.308452) # numeric string unfriendly_id? 9.190000 0.040000 9.230000 ( 9.252890) # test_string friendly_id? 8.380000 0.010000 8.390000 ( 8.411762) # test_string unfriendly_id? 8.450000 0.010000 8.460000 ( 8.463662) # From the ObjectUtils docs... # 123.friendly_id? #=> false # :id.friendly_id? #=> false # {:name => 'joe'}.friendly_id? #=> false # ['name = ?', 'joe'].friendly_id? #=> false # nil.friendly_id? #=> false # "123".friendly_id? #=> nil # "abc123".friendly_id? #=> true Book = Class.new ActiveRecord::Base test_integer = 123 test_active_record_object = Book.new test_hash = {name: "joe"} test_nil = nil test_numeric_string = "123" test_string = "abc123" N = 5_000_000 Benchmark.bmbm do |x| x.report("integer friendly_id?") { N.times { test_integer.friendly_id? } } x.report("integer unfriendly_id?") { N.times { test_integer.unfriendly_id? } } x.report("AR::Base friendly_id?") { N.times { test_active_record_object.friendly_id? } } x.report("AR::Base unfriendly_id?") { N.times { test_active_record_object.unfriendly_id? } } x.report("hash friendly_id?") { N.times { test_hash.friendly_id? } } x.report("hash unfriendly_id?") { N.times { test_hash.unfriendly_id? } } x.report("nil friendly_id?") { N.times { test_nil.friendly_id? } } x.report("nil unfriendly_id?") { N.times { test_nil.unfriendly_id? } } x.report("numeric string friendly_id?") { N.times { test_numeric_string.friendly_id? } } x.report("numeric string unfriendly_id?") { N.times { test_numeric_string.unfriendly_id? } } x.report("test_string friendly_id?") { N.times { test_string.friendly_id? } } x.report("test_string unfriendly_id?") { N.times { test_string.unfriendly_id? } } end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id.rb
lib/friendly_id.rb
require "active_record" require "friendly_id/base" require "friendly_id/object_utils" require "friendly_id/configuration" require "friendly_id/finder_methods" # @guide begin # # ## About FriendlyId # # FriendlyId is an add-on to Ruby's Active Record that allows you to replace ids # in your URLs with strings: # # # without FriendlyId # http://example.com/states/4323454 # # # with FriendlyId # http://example.com/states/washington # # It requires few changes to your application code and offers flexibility, # performance and a well-documented codebase. # # ### Core Concepts # # #### Slugs # # The concept of *slugs* is at the heart of FriendlyId. # # A slug is the part of a URL which identifies a page using human-readable # keywords, rather than an opaque identifier such as a numeric id. This can make # your application more friendly both for users and search engines. # # #### Finders: Slugs Act Like Numeric IDs # # To the extent possible, FriendlyId lets you treat text-based identifiers like # normal IDs. This means that you can perform finds with slugs just like you do # with numeric ids: # # Person.find(82542335) # Person.friendly.find("joe") # # @guide end module FriendlyId autoload :History, "friendly_id/history" autoload :Slug, "friendly_id/slug" autoload :SimpleI18n, "friendly_id/simple_i18n" autoload :Reserved, "friendly_id/reserved" autoload :Scoped, "friendly_id/scoped" autoload :Slugged, "friendly_id/slugged" autoload :Finders, "friendly_id/finders" autoload :SequentiallySlugged, "friendly_id/sequentially_slugged" # FriendlyId takes advantage of `extended` to do basic model setup, primarily # extending {FriendlyId::Base} to add {FriendlyId::Base#friendly_id # friendly_id} as a class method. # # Previous versions of FriendlyId simply patched ActiveRecord::Base, but this # version tries to be less invasive. # # In addition to adding {FriendlyId::Base#friendly_id friendly_id}, the class # instance variable +@friendly_id_config+ is added. This variable is an # instance of an anonymous subclass of {FriendlyId::Configuration}. This # allows subsequently loaded modules like {FriendlyId::Slugged} and # {FriendlyId::Scoped} to add functionality to the configuration class only # for the current class, rather than monkey patching # {FriendlyId::Configuration} directly. This isolates other models from large # feature changes an addon to FriendlyId could potentially introduce. # # The upshot of this is, you can have two Active Record models that both have # a @friendly_id_config, but each config object can have different methods # and behaviors depending on what modules have been loaded, without # conflicts. Keep this in mind if you're hacking on FriendlyId. # # For examples of this, see the source for {Scoped.included}. def self.extended(model_class) return if model_class.respond_to? :friendly_id class << model_class alias_method :relation_without_friendly_id, :relation end model_class.class_eval do extend Base @friendly_id_config = Class.new(Configuration).new(self) FriendlyId.defaults.call @friendly_id_config include Model end end # Allow developers to `include` FriendlyId or `extend` it. def self.included(model_class) model_class.extend self end # Set global defaults for all models using FriendlyId. # # The default defaults are to use the `:reserved` module and nothing else. # # @example # FriendlyId.defaults do |config| # config.base :name # config.use :slugged # end def self.defaults(&block) @defaults = block if block @defaults ||= ->(config) { config.use :reserved } end # Set the ActiveRecord table name prefix to friendly_id_ # # This makes 'slugs' into 'friendly_id_slugs' and also respects any # 'global' table_name_prefix set on ActiveRecord::Base. def self.table_name_prefix "#{ActiveRecord::Base.table_name_prefix}friendly_id_" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/sequentially_slugged.rb
lib/friendly_id/sequentially_slugged.rb
require_relative "sequentially_slugged/calculator" module FriendlyId module SequentiallySlugged def self.setup(model_class) model_class.friendly_id_config.use :slugged end def resolve_friendly_id_conflict(candidate_slugs) candidate = candidate_slugs.first return if candidate.nil? Calculator.new( scope_for_slug_generator, candidate, slug_column, friendly_id_config.sequence_separator, slug_base_class ).next_slug end private def slug_base_class if friendly_id_config.uses?(:history) Slug else self.class.base_class end end def slug_column if friendly_id_config.uses?(:history) :slug else friendly_id_config.slug_column end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/simple_i18n.rb
lib/friendly_id/simple_i18n.rb
require "i18n" module FriendlyId # @guide begin # # ## Translating Slugs Using Simple I18n # # The {FriendlyId::SimpleI18n SimpleI18n} module adds very basic i18n support to # FriendlyId. # # In order to use this module, your model must have a slug column for each locale. # By default FriendlyId looks for columns named, for example, "slug_en", # "slug_es", "slug_pt_br", etc. The first part of the name can be configured by # passing the `:slug_column` option if you choose. Note that the column for the # default locale must also include the locale in its name. # # This module is most suitable to applications that need to support few locales. # If you need to support two or more locales, you may wish to use the # friendly_id_globalize gem instead. # # ### Example migration # # def self.up # create_table :posts do |t| # t.string :title # t.string :slug_en # t.string :slug_es # t.string :slug_pt_br # t.text :body # end # add_index :posts, :slug_en # add_index :posts, :slug_es # add_index :posts, :slug_pt_br # end # # ### Finds # # Finds will take into consideration the current locale: # # I18n.locale = :es # Post.friendly.find("la-guerra-de-las-galaxias") # I18n.locale = :en # Post.friendly.find("star-wars") # I18n.locale = :"pt-BR" # Post.friendly.find("guerra-das-estrelas") # # To find a slug by an explicit locale, perform the find inside a block # passed to I18n's `with_locale` method: # # I18n.with_locale(:es) do # Post.friendly.find("la-guerra-de-las-galaxias") # end # # ### Creating Records # # When new records are created, the slug is generated for the current locale only. # # ### Translating Slugs # # To translate an existing record's friendly_id, use # {FriendlyId::SimpleI18n::Model#set_friendly_id}. This will ensure that the slug # you add is properly escaped, transliterated and sequenced: # # post = Post.create :name => "Star Wars" # post.set_friendly_id("La guerra de las galaxias", :es) # # If you don't pass in a locale argument, FriendlyId::SimpleI18n will just use the # current locale: # # I18n.with_locale(:es) do # post.set_friendly_id("La guerra de las galaxias") # end # # @guide end module SimpleI18n # FriendlyId::Config.use will invoke this method when present, to allow # loading dependent modules prior to overriding them when necessary. def self.setup(model_class) model_class.friendly_id_config.use :slugged end def self.included(model_class) model_class.class_eval do friendly_id_config.class.send :include, Configuration include Model end end module Model def set_friendly_id(text, locale = nil) I18n.with_locale(locale || I18n.locale) do set_slug(normalize_friendly_id(text)) end end def slug=(value) super write_attribute friendly_id_config.slug_column, value end end module Configuration def slug_column "#{super}_#{locale_suffix}" end private def locale_suffix I18n.locale.to_s.underscore end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/version.rb
lib/friendly_id/version.rb
module FriendlyId VERSION = "5.6.0".freeze end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/scoped.rb
lib/friendly_id/scoped.rb
require "friendly_id/slugged" module FriendlyId # @guide begin # # ## Unique Slugs by Scope # # The {FriendlyId::Scoped} module allows FriendlyId to generate unique slugs # within a scope. # # This allows, for example, two restaurants in different cities to have the slug # `joes-diner`: # # class Restaurant < ActiveRecord::Base # extend FriendlyId # belongs_to :city # friendly_id :name, :use => :scoped, :scope => :city # end # # class City < ActiveRecord::Base # extend FriendlyId # has_many :restaurants # friendly_id :name, :use => :slugged # end # # City.friendly.find("seattle").restaurants.friendly.find("joes-diner") # City.friendly.find("chicago").restaurants.friendly.find("joes-diner") # # Without :scoped in this case, one of the restaurants would have the slug # `joes-diner` and the other would have `joes-diner-f9f3789a-daec-4156-af1d-fab81aa16ee5`. # # The value for the `:scope` option can be the name of a `belongs_to` relation, or # a column. # # Additionally, the `:scope` option can receive an array of scope values: # # class Cuisine < ActiveRecord::Base # extend FriendlyId # has_many :restaurants # friendly_id :name, :use => :slugged # end # # class City < ActiveRecord::Base # extend FriendlyId # has_many :restaurants # friendly_id :name, :use => :slugged # end # # class Restaurant < ActiveRecord::Base # extend FriendlyId # belongs_to :city # friendly_id :name, :use => :scoped, :scope => [:city, :cuisine] # end # # All supplied values will be used to determine scope. # # ### Finding Records by Friendly ID # # If you are using scopes your friendly ids may not be unique, so a simple find # like: # # Restaurant.friendly.find("joes-diner") # # may return the wrong record. In these cases it's best to query through the # relation: # # @city.restaurants.friendly.find("joes-diner") # # Alternatively, you could pass the scope value as a query parameter: # # Restaurant.where(:city_id => @city.id).friendly.find("joes-diner") # # # ### Finding All Records That Match a Scoped ID # # Query the slug column directly: # # Restaurant.where(:slug => "joes-diner") # # ### Routes for Scoped Models # # Recall that FriendlyId is a database-centric library, and does not set up any # routes for scoped models. You must do this yourself in your application. Here's # an example of one way to set this up: # # # in routes.rb # resources :cities do # resources :restaurants # end # # # in views # <%= link_to 'Show', [@city, @restaurant] %> # # # in controllers # @city = City.friendly.find(params[:city_id]) # @restaurant = @city.restaurants.friendly.find(params[:id]) # # # URLs: # http://example.org/cities/seattle/restaurants/joes-diner # http://example.org/cities/chicago/restaurants/joes-diner # # @guide end module Scoped # FriendlyId::Config.use will invoke this method when present, to allow # loading dependent modules prior to overriding them when necessary. def self.setup(model_class) model_class.friendly_id_config.use :slugged end # Sets up behavior and configuration options for FriendlyId's scoped slugs # feature. def self.included(model_class) model_class.class_eval do friendly_id_config.class.send :include, Configuration end end def serialized_scope friendly_id_config.scope_columns.sort.map { |column| "#{column}:#{send(column)}" }.join(",") end def scope_for_slug_generator if friendly_id_config.uses?(:History) return super end relation = self.class.base_class.unscoped.friendly friendly_id_config.scope_columns.each do |column| relation = relation.where(column => send(column)) end primary_key_name = self.class.primary_key relation.where(self.class.arel_table[primary_key_name].not_eq(send(primary_key_name))) end private :scope_for_slug_generator def slug_generator friendly_id_config.slug_generator_class.new(scope_for_slug_generator, friendly_id_config) end private :slug_generator def should_generate_new_friendly_id? (changed & friendly_id_config.scope_columns).any? || super end # This module adds the `:scope` configuration option to # {FriendlyId::Configuration FriendlyId::Configuration}. module Configuration # Gets the scope value. # # When setting this value, the argument should be a symbol referencing a # `belongs_to` relation, or a column. # # @return Symbol The scope value attr_accessor :scope # Gets the scope columns. # # Checks to see if the `:scope` option passed to # {FriendlyId::Base#friendly_id} refers to a relation, and if so, returns # the realtion's foreign key. Otherwise it assumes the option value was # the name of column and returns it cast to a String. # # @return String The scope column def scope_columns [@scope].flatten.map { |s| (reflection_foreign_key(s) or s).to_s } end private def reflection_foreign_key(scope) reflection = model_class.reflections[scope] || model_class.reflections[scope.to_s] reflection.try(:foreign_key) end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/finders.rb
lib/friendly_id/finders.rb
module FriendlyId # @guide begin # # ## Performing Finds with FriendlyId # # FriendlyId offers enhanced finders which will search for your record by # friendly id, and fall back to the numeric id if necessary. This makes it easy # to add FriendlyId to an existing application with minimal code modification. # # By default, these methods are available only on the `friendly` scope: # # Restaurant.friendly.find('plaza-diner') #=> works # Restaurant.friendly.find(23) #=> also works # Restaurant.find(23) #=> still works # Restaurant.find('plaza-diner') #=> will not work # # ### Restoring FriendlyId 4.0-style finders # # Prior to version 5.0, FriendlyId overrode the default finder methods to perform # friendly finds all the time. This required modifying parts of Rails that did # not have a public API, which was harder to maintain and at times caused # compatiblity problems. In 5.0 we decided to change the library's defaults and add # the friendly finder methods only to the `friendly` scope in order to boost # compatiblity. However, you can still opt-in to original functionality very # easily by using the `:finders` addon: # # class Restaurant < ActiveRecord::Base # extend FriendlyId # # scope :active, -> {where(:active => true)} # # friendly_id :name, :use => [:slugged, :finders] # end # # Restaurant.friendly.find('plaza-diner') #=> works # Restaurant.find('plaza-diner') #=> now also works # Restaurant.active.find('plaza-diner') #=> now also works # # ### Updating your application to use FriendlyId's finders # # Unless you've chosen to use the `:finders` addon, be sure to modify the finders # in your controllers to use the `friendly` scope. For example: # # # before # def set_restaurant # @restaurant = Restaurant.find(params[:id]) # end # # # after # def set_restaurant # @restaurant = Restaurant.friendly.find(params[:id]) # end # # #### Active Admin # # Unless you use the `:finders` addon, you should modify your admin controllers # for models that use FriendlyId with something similar to the following: # # controller do # def find_resource # scoped_collection.friendly.find(params[:id]) # end # end # # @guide end module Finders module ClassMethods if (ActiveRecord::VERSION::MAJOR == 4) && (ActiveRecord::VERSION::MINOR == 0) def relation_delegate_class(klass) relation_class_name = :"#{klass.to_s.gsub("::", "_")}_#{to_s.gsub("::", "_")}" klass.const_get(relation_class_name) end end end def self.setup(model_class) model_class.instance_eval do relation.class.send(:include, friendly_id_config.finder_methods) if (ActiveRecord::VERSION::MAJOR == 4 && ActiveRecord::VERSION::MINOR == 2) || ActiveRecord::VERSION::MAJOR >= 5 model_class.send(:extend, friendly_id_config.finder_methods) end end # Support for friendly finds on associations for Rails 4.0.1 and above. if ::ActiveRecord.const_defined?("AssociationRelation") model_class.extend(ClassMethods) association_relation_delegate_class = model_class.relation_delegate_class(::ActiveRecord::AssociationRelation) association_relation_delegate_class.send(:include, model_class.friendly_id_config.finder_methods) end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/slug_generator.rb
lib/friendly_id/slug_generator.rb
module FriendlyId # The default slug generator offers functionality to check slug candidates for # availability. class SlugGenerator def initialize(scope, config) @scope = scope @config = config end def available?(slug) if @config.uses?(::FriendlyId::Reserved) && @config.reserved_words.present? && @config.treat_reserved_as_conflict return false if @config.reserved_words.include?(slug) end if @config.treat_numeric_as_conflict && purely_numeric_slug?(slug) return false end !@scope.exists_by_friendly_id?(slug) end def generate(candidates) candidates.each { |c| return c if available?(c) } nil end private def purely_numeric_slug?(slug) return false unless slug begin Integer(slug, 10).to_s == slug.to_s rescue ArgumentError, TypeError false end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/initializer.rb
lib/friendly_id/initializer.rb
# FriendlyId Global Configuration # # Use this to set up shared configuration options for your entire application. # Any of the configuration options shown here can also be applied to single # models by passing arguments to the `friendly_id` class method or defining # methods in your model. # # To learn more, check out the guide: # # http://norman.github.io/friendly_id/file.Guide.html FriendlyId.defaults do |config| # ## Reserved Words # # Some words could conflict with Rails's routes when used as slugs, or are # undesirable to allow as slugs. Edit this list as needed for your app. config.use :reserved config.reserved_words = %w[new edit index session login logout users admin stylesheets assets javascripts images] # This adds an option to treat reserved words as conflicts rather than exceptions. # When there is no good candidate, a UUID will be appended, matching the existing # conflict behavior. # config.treat_reserved_as_conflict = true # ## Friendly Finders # # Uncomment this to use friendly finders in all models. By default, if # you wish to find a record by its friendly id, you must do: # # MyModel.friendly.find('foo') # # If you uncomment this, you can do: # # MyModel.find('foo') # # This is significantly more convenient but may not be appropriate for # all applications, so you must explicitly opt-in to this behavior. You can # always also configure it on a per-model basis if you prefer. # # Something else to consider is that using the :finders addon boosts # performance because it will avoid Rails-internal code that makes runtime # calls to `Module.extend`. # # config.use :finders # # ## Slugs # # Most applications will use the :slugged module everywhere. If you wish # to do so, uncomment the following line. # # config.use :slugged # # By default, FriendlyId's :slugged addon expects the slug column to be named # 'slug', but you can change it if you wish. # # config.slug_column = 'slug' # # By default, slug has no size limit, but you can change it if you wish. # # config.slug_limit = 255 # # When FriendlyId can not generate a unique ID from your base method, it appends # a UUID, separated by a single dash. You can configure the character used as the # separator. If you're upgrading from FriendlyId 4, you may wish to replace this # with two dashes. # # config.sequence_separator = '-' # # Note that you must use the :slugged addon **prior** to the line which # configures the sequence separator, or else FriendlyId will raise an undefined # method error. # # ## Tips and Tricks # # ### Controlling when slugs are generated # # As of FriendlyId 5.0, new slugs are generated only when the slug field is # nil, but if you're using a column as your base method can change this # behavior by overriding the `should_generate_new_friendly_id?` method that # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave # more like 4.0. # Note: Use(include) Slugged module in the config if using the anonymous module. # If you have `friendly_id :name, use: slugged` in the model, Slugged module # is included after the anonymous module defined in the initializer, so it # overrides the `should_generate_new_friendly_id?` method from the anonymous module. # # config.use :slugged # config.use Module.new { # def should_generate_new_friendly_id? # slug.blank? || <your_column_name_here>_changed? # end # } # # FriendlyId uses Rails's `parameterize` method to generate slugs, but for # languages that don't use the Roman alphabet, that's not usually sufficient. # Here we use the Babosa library to transliterate Russian Cyrillic slugs to # ASCII. If you use this, don't forget to add "babosa" to your Gemfile. # # config.use Module.new { # def normalize_friendly_id(text) # text.to_slug.normalize! :transliterations => [:russian, :latin] # end # } end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/candidates.rb
lib/friendly_id/candidates.rb
require "securerandom" module FriendlyId # This class provides the slug candidate functionality. # @see FriendlyId::Slugged class Candidates include Enumerable def initialize(object, *array) @object = object @raw_candidates = to_candidate_array(object, array.flatten(1)) end def each(*args, &block) return candidates unless block candidates.each { |candidate| yield candidate } end private def candidates @candidates ||= begin candidates = normalize(@raw_candidates) filter(candidates) end end def normalize(candidates) candidates.map do |candidate| @object.normalize_friendly_id(candidate.map(&:call).join(" ")) end.select { |x| wanted?(x) } end def filter(candidates) unless candidates.all? { |x| reserved?(x) } candidates.reject! { |x| reserved?(x) } end candidates end def to_candidate_array(object, array) array.map do |candidate| case candidate when String [-> { candidate }] when Array to_candidate_array(object, candidate).flatten when Symbol [object.method(candidate)] else if candidate.respond_to?(:call) [candidate] else [-> { candidate.to_s }] end end end end def wanted?(slug) slug.present? end def reserved?(slug) config = @object.friendly_id_config return false unless config.uses? ::FriendlyId::Reserved return false unless config.reserved_words config.reserved_words.include?(slug) end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/slugged.rb
lib/friendly_id/slugged.rb
require "friendly_id/slug_generator" require "friendly_id/candidates" module FriendlyId # @guide begin # # ## Slugged Models # # FriendlyId can use a separate column to store slugs for models which require # some text processing. # # For example, blog applications typically use a post title to provide the basis # of a search engine friendly URL. Such identifiers typically lack uppercase # characters, use ASCII to approximate UTF-8 characters, and strip out other # characters which may make them aesthetically unappealing or error-prone when # used in a URL. # # class Post < ActiveRecord::Base # extend FriendlyId # friendly_id :title, :use => :slugged # end # # @post = Post.create(:title => "This is the first post!") # @post.friendly_id # returns "this-is-the-first-post" # redirect_to @post # the URL will be /posts/this-is-the-first-post # # In general, use slugs by default unless you know for sure you don't need them. # To activate the slugging functionality, use the {FriendlyId::Slugged} module. # # FriendlyId will generate slugs from a method or column that you specify, and # store them in a field in your model. By default, this field must be named # `:slug`, though you may change this using the # {FriendlyId::Slugged::Configuration#slug_column slug_column} configuration # option. You should add an index to this column, and in most cases, make it # unique. You may also wish to constrain it to NOT NULL, but this depends on your # app's behavior and requirements. # # ### Example Setup # # # your model # class Post < ActiveRecord::Base # extend FriendlyId # friendly_id :title, :use => :slugged # validates_presence_of :title, :slug, :body # end # # # a migration # class CreatePosts < ActiveRecord::Migration # def self.up # create_table :posts do |t| # t.string :title, :null => false # t.string :slug, :null => false # t.text :body # end # # add_index :posts, :slug, :unique => true # end # # def self.down # drop_table :posts # end # end # # ### Working With Slugs # # #### Formatting # # By default, FriendlyId uses Active Support's # [parameterize](http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize) # method to create slugs. This method will intelligently replace spaces with # dashes, and Unicode Latin characters with ASCII approximations: # # movie = Movie.create! :title => "Der Preis fürs Überleben" # movie.slug #=> "der-preis-furs-uberleben" # # #### Column or Method? # # FriendlyId always uses a method as the basis of the slug text - not a column. At # first glance, this may sound confusing, but remember that Active Record provides # methods for each column in a model's associated table, and that's what # FriendlyId uses. # # Here's an example of a class that uses a custom method to generate the slug: # # class Person < ActiveRecord::Base # extend FriendlyId # friendly_id :name_and_location, use: :slugged # # def name_and_location # "#{name} from #{location}" # end # end # # bob = Person.create! :name => "Bob Smith", :location => "New York City" # bob.friendly_id #=> "bob-smith-from-new-york-city" # # FriendlyId refers to this internally as the "base" method. # # #### Uniqueness # # When you try to insert a record that would generate a duplicate friendly id, # FriendlyId will append a UUID to the generated slug to ensure uniqueness: # # car = Car.create :title => "Peugeot 206" # car2 = Car.create :title => "Peugeot 206" # # car.friendly_id #=> "peugeot-206" # car2.friendly_id #=> "peugeot-206-f9f3789a-daec-4156-af1d-fab81aa16ee5" # # Previous versions of FriendlyId appended a numeric sequence to make slugs # unique, but this was removed to simplify using FriendlyId in concurrent code. # # #### Candidates # # Since UUIDs are ugly, FriendlyId provides a "slug candidates" functionality to # let you specify alternate slugs to use in the event the one you want to use is # already taken. For example: # # class Restaurant < ActiveRecord::Base # extend FriendlyId # friendly_id :slug_candidates, use: :slugged # # # Try building a slug based on the following fields in # # increasing order of specificity. # def slug_candidates # [ # :name, # [:name, :city], # [:name, :street, :city], # [:name, :street_number, :street, :city] # ] # end # end # # r1 = Restaurant.create! name: 'Plaza Diner', city: 'New Paltz' # r2 = Restaurant.create! name: 'Plaza Diner', city: 'Kingston' # # r1.friendly_id #=> 'plaza-diner' # r2.friendly_id #=> 'plaza-diner-kingston' # # To use candidates, make your FriendlyId base method return an array. The # method need not be named `slug_candidates`; it can be anything you want. The # array may contain any combination of symbols, strings, procs or lambdas and # will be evaluated lazily and in order. If you include symbols, FriendlyId will # invoke a method on your model class with the same name. Strings will be # interpreted literally. Procs and lambdas will be called and their return values # used as the basis of the friendly id. If none of the candidates can generate a # unique slug, then FriendlyId will append a UUID to the first candidate as a # last resort. # # #### Sequence Separator # # By default, FriendlyId uses a dash to separate the slug from a sequence. # # You can change this with the {FriendlyId::Slugged::Configuration#sequence_separator # sequence_separator} configuration option. # # #### Avoiding Numeric Slugs # # Purely numeric slugs like "123" can create ambiguity in Rails routing - they could # be interpreted as either a friendly slug or a database ID. To prevent this, you can # configure FriendlyId to treat numeric slugs as conflicts and add a UUID suffix: # # class Product < ActiveRecord::Base # extend FriendlyId # friendly_id :sku, use: :slugged # friendly_id_config.treat_numeric_as_conflict = true # end # # product = Product.create! sku: "123" # product.slug #=> "123-f9f3789a-daec-4156-af1d-fab81aa16ee5" # # This only affects purely numeric slugs. Alphanumeric slugs like "product-123" # or "abc123" will work normally. # # #### Providing Your Own Slug Processing Method # # You can override {FriendlyId::Slugged#normalize_friendly_id} in your model for # total control over the slug format. It will be invoked for any generated slug, # whether for a single slug or for slug candidates. # # #### Deciding When to Generate New Slugs # # As of FriendlyId 5.0, slugs are only generated when the `slug` field is nil. If # you want a slug to be regenerated,set the slug field to nil: # # restaurant.friendly_id # joes-diner # restaurant.name = "The Plaza Diner" # restaurant.save! # restaurant.friendly_id # joes-diner # restaurant.slug = nil # restaurant.save! # restaurant.friendly_id # the-plaza-diner # # You can also override the # {FriendlyId::Slugged#should_generate_new_friendly_id?} method, which lets you # control exactly when new friendly ids are set: # # class Post < ActiveRecord::Base # extend FriendlyId # friendly_id :title, :use => :slugged # # def should_generate_new_friendly_id? # title_changed? # end # end # # If you want to extend the default behavior but add your own conditions, # don't forget to invoke `super` from your implementation: # # class Category < ActiveRecord::Base # extend FriendlyId # friendly_id :name, :use => :slugged # # def should_generate_new_friendly_id? # name_changed? || super # end # end # # #### Locale-specific Transliterations # # Active Support's `parameterize` uses # [transliterate](http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate), # which in turn can use I18n's transliteration rules to consider the current # locale when replacing Latin characters: # # # config/locales/de.yml # de: # i18n: # transliterate: # rule: # ü: "ue" # ö: "oe" # etc... # # movie = Movie.create! :title => "Der Preis fürs Überleben" # movie.slug #=> "der-preis-fuers-ueberleben" # # This functionality was in fact taken from earlier versions of FriendlyId. # # #### Gotchas: Common Problems # # FriendlyId uses a before_validation callback to generate and set the slug. This # means that if you create two model instances before saving them, it's possible # they will generate the same slug, and the second save will fail. # # This can happen in two fairly normal cases: the first, when a model using nested # attributes creates more than one record for a model that uses friendly_id. The # second, in concurrent code, either in threads or multiple processes. # # To solve the nested attributes issue, I recommend simply avoiding them when # creating more than one nested record for a model that uses FriendlyId. See [this # Github issue](https://github.com/norman/friendly_id/issues/185) for discussion. # # @guide end module Slugged # Sets up behavior and configuration options for FriendlyId's slugging # feature. def self.included(model_class) model_class.friendly_id_config.instance_eval do self.class.send :include, Configuration self.slug_generator_class ||= SlugGenerator defaults[:slug_column] ||= "slug" defaults[:sequence_separator] ||= "-" end model_class.before_validation :set_slug model_class.before_save :set_slug model_class.after_validation :unset_slug_if_invalid end # Process the given value to make it suitable for use as a slug. # # This method is not intended to be invoked directly; FriendlyId uses it # internally to process strings into slugs. # # However, if FriendlyId's default slug generation doesn't suit your needs, # you can override this method in your model class to control exactly how # slugs are generated. # # ### Example # # class Person < ActiveRecord::Base # extend FriendlyId # friendly_id :name_and_location # # def name_and_location # "#{name} from #{location}" # end # # # Use default slug, but upper case and with underscores # def normalize_friendly_id(string) # super.upcase.gsub("-", "_") # end # end # # bob = Person.create! :name => "Bob Smith", :location => "New York City" # bob.friendly_id #=> "BOB_SMITH_FROM_NEW_YORK_CITY" # # ### More Resources # # You might want to look into Babosa[https://github.com/norman/babosa], # which is the slugging library used by FriendlyId prior to version 4, which # offers some specialized functionality missing from Active Support. # # @param [#to_s] value The value used as the basis of the slug. # @return The candidate slug text, without a sequence. def normalize_friendly_id(value) value = value.to_s.parameterize value = value[0...friendly_id_config.slug_limit] if friendly_id_config.slug_limit value end # Whether to generate a new slug. # # You can override this method in your model if, for example, you only want # slugs to be generated once, and then never updated. def should_generate_new_friendly_id? send(friendly_id_config.slug_column).nil? && !send(friendly_id_config.base).nil? end # Public: Resolve conflicts. # # This method adds UUID to first candidate and truncates (if `slug_limit` is set). # # Examples: # # resolve_friendly_id_conflict(['12345']) # # => '12345-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # # FriendlyId.defaults { |config| config.slug_limit = 40 } # resolve_friendly_id_conflict(['12345']) # # => '123-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # # candidates - the Array with candidates. # # Returns the String with new slug. def resolve_friendly_id_conflict(candidates) uuid = SecureRandom.uuid [ apply_slug_limit(candidates.first, uuid), uuid ].compact.join(friendly_id_config.sequence_separator) end # Private: Apply slug limit to candidate. # # candidate - the String with candidate. # uuid - the String with UUID. # # Return the String with truncated candidate. def apply_slug_limit(candidate, uuid) return candidate unless candidate && friendly_id_config.slug_limit candidate[0...candidate_limit(uuid)] end private :apply_slug_limit # Private: Get max length of candidate. # # uuid - the String with UUID. # # Returns the Integer with max length. def candidate_limit(uuid) [ friendly_id_config.slug_limit - uuid.size - friendly_id_config.sequence_separator.size, 0 ].max end private :candidate_limit # Sets the slug. def set_slug(normalized_slug = nil) if should_generate_new_friendly_id? candidates = FriendlyId::Candidates.new(self, normalized_slug || send(friendly_id_config.base)) slug = slug_generator.generate(candidates) || resolve_friendly_id_conflict(candidates) send "#{friendly_id_config.slug_column}=", slug end end private :set_slug def scope_for_slug_generator scope = self.class.base_class.unscoped scope = scope.friendly unless scope.respond_to?(:exists_by_friendly_id?) primary_key_name = self.class.primary_key scope.where(self.class.base_class.arel_table[primary_key_name].not_eq(send(primary_key_name))) end private :scope_for_slug_generator def slug_generator friendly_id_config.slug_generator_class.new(scope_for_slug_generator, friendly_id_config) end private :slug_generator def unset_slug_if_invalid if errors.key?(friendly_id_config.query_field) && attribute_changed?(friendly_id_config.query_field.to_s) diff = changes[friendly_id_config.query_field] send "#{friendly_id_config.slug_column}=", diff.first end end private :unset_slug_if_invalid # This module adds the `:slug_column`, and `:slug_limit`, and `:sequence_separator`, # and `:slug_generator_class` configuration options to # {FriendlyId::Configuration FriendlyId::Configuration}. module Configuration attr_writer :slug_column, :slug_limit, :sequence_separator attr_accessor :slug_generator_class, :treat_numeric_as_conflict # Makes FriendlyId use the slug column for querying. # @return String The slug column. def query_field slug_column end # The string used to separate a slug base from a numeric sequence. # # You can change the default separator by setting the # {FriendlyId::Slugged::Configuration#sequence_separator # sequence_separator} configuration option. # @return String The sequence separator string. Defaults to "`-`". def sequence_separator @sequence_separator ||= defaults[:sequence_separator] end # The column that will be used to store the generated slug. def slug_column @slug_column ||= defaults[:slug_column] end # The limit that will be used for slug. def slug_limit @slug_limit ||= defaults[:slug_limit] end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/reserved.rb
lib/friendly_id/reserved.rb
module FriendlyId # @guide begin # # ## Reserved Words # # The {FriendlyId::Reserved Reserved} module adds the ability to exclude a list of # words from use as FriendlyId slugs. # # With Ruby on Rails, FriendlyId's generator generates an initializer that # reserves some words such as "new" and "edit" using {FriendlyId.defaults # FriendlyId.defaults}. # # Note that the error messages for fields will appear on the field # `:friendly_id`. If you are using Rails's scaffolded form errors display, then # it will have no field to highlight. If you'd like to change this so that # scaffolding works as expected, one way to accomplish this is to move the error # message to a different field. For example: # # class Person < ActiveRecord::Base # extend FriendlyId # friendly_id :name, use: :slugged # # after_validation :move_friendly_id_error_to_name # # def move_friendly_id_error_to_name # errors.add :name, *errors.delete(:friendly_id) if errors[:friendly_id].present? # end # end # # @guide end module Reserved # When included, this module adds configuration options to the model class's # friendly_id_config. def self.included(model_class) model_class.class_eval do friendly_id_config.class.send :include, Reserved::Configuration validates_exclusion_of :friendly_id, in: ->(_) { friendly_id_config.reserved_words || [] } end end # This module adds the `:reserved_words` configuration option to # {FriendlyId::Configuration FriendlyId::Configuration}. module Configuration attr_accessor :reserved_words attr_accessor :treat_reserved_as_conflict end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/slug.rb
lib/friendly_id/slug.rb
module FriendlyId # A FriendlyId slug stored in an external table. # # @see FriendlyId::History class Slug < ActiveRecord::Base belongs_to :sluggable, polymorphic: true def sluggable sluggable_type.constantize.unscoped { super } end def to_param slug end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/base.rb
lib/friendly_id/base.rb
module FriendlyId # @guide begin # # ## Setting Up FriendlyId in Your Model # # To use FriendlyId in your ActiveRecord models, you must first either extend or # include the FriendlyId module (it makes no difference), then invoke the # {FriendlyId::Base#friendly_id friendly_id} method to configure your desired # options: # # class Foo < ActiveRecord::Base # include FriendlyId # friendly_id :bar, :use => [:slugged, :simple_i18n] # end # # The most important option is `:use`, which you use to tell FriendlyId which # addons it should use. See the documentation for {FriendlyId::Base#friendly_id} for a list of all # available addons, or skim through the rest of the docs to get a high-level # overview. # # *A note about single table inheritance (STI): you must extend FriendlyId in # all classes that participate in STI, both your parent classes and their # children.* # # ### The Default Setup: Simple Models # # The simplest way to use FriendlyId is with a model that has a uniquely indexed # column with no spaces or special characters, and that is seldom or never # updated. The most common example of this is a user name: # # class User < ActiveRecord::Base # extend FriendlyId # friendly_id :login # validates_format_of :login, :with => /\A[a-z0-9]+\z/i # end # # @user = User.friendly.find "joe" # the old User.find(1) still works, too # @user.to_param # returns "joe" # redirect_to @user # the URL will be /users/joe # # In this case, FriendlyId assumes you want to use the column as-is; it will never # modify the value of the column, and your application should ensure that the # value is unique and admissible in a URL: # # class City < ActiveRecord::Base # extend FriendlyId # friendly_id :name # end # # @city.friendly.find "Viña del Mar" # redirect_to @city # the URL will be /cities/Viña%20del%20Mar # # Writing the code to process an arbitrary string into a good identifier for use # in a URL can be repetitive and surprisingly tricky, so for this reason it's # often better and easier to use {FriendlyId::Slugged slugs}. # # @guide end module Base # Configure FriendlyId's behavior in a model. # # class Post < ActiveRecord::Base # extend FriendlyId # friendly_id :title, :use => :slugged # end # # When given the optional block, this method will yield the class's instance # of {FriendlyId::Configuration} to the block before evaluating other # arguments, so configuration values set in the block may be overwritten by # the arguments. This order was chosen to allow passing the same proc to # multiple models, while being able to override the values it sets. Here is # a contrived example: # # $friendly_id_config_proc = Proc.new do |config| # config.base = :name # config.use :slugged # end # # class Foo < ActiveRecord::Base # extend FriendlyId # friendly_id &$friendly_id_config_proc # end # # class Bar < ActiveRecord::Base # extend FriendlyId # friendly_id :title, &$friendly_id_config_proc # end # # However, it's usually better to use {FriendlyId.defaults} for this: # # FriendlyId.defaults do |config| # config.base = :name # config.use :slugged # end # # class Foo < ActiveRecord::Base # extend FriendlyId # end # # class Bar < ActiveRecord::Base # extend FriendlyId # friendly_id :title # end # # In general you should use the block syntax either because of your personal # aesthetic preference, or because you need to share some functionality # between multiple models that can't be well encapsulated by # {FriendlyId.defaults}. # # ### Order Method Calls in a Block vs Ordering Options # # When calling this method without a block, you may set the hash options in # any order. # # However, when using block-style invocation, be sure to call # FriendlyId::Configuration's {FriendlyId::Configuration#use use} method # *prior* to the associated configuration options, because it will include # modules into your class, and these modules in turn may add required # configuration options to the `@friendly_id_configuraton`'s class: # # class Person < ActiveRecord::Base # friendly_id do |config| # # This will work # config.use :slugged # config.sequence_separator = ":" # end # end # # class Person < ActiveRecord::Base # friendly_id do |config| # # This will fail # config.sequence_separator = ":" # config.use :slugged # end # end # # ### Including Your Own Modules # # Because :use can accept a name or a Module, {FriendlyId.defaults defaults} # can be a convenient place to set up behavior common to all classes using # FriendlyId. You can include any module, or more conveniently, define one # on-the-fly. For example, let's say you want to make # [Babosa](http://github.com/norman/babosa) the default slugging library in # place of Active Support, and transliterate all slugs from Russian Cyrillic # to ASCII: # # require "babosa" # # FriendlyId.defaults do |config| # config.base = :name # config.use :slugged # config.use Module.new { # def normalize_friendly_id(text) # text.to_slug.normalize! :transliterations => [:russian, :latin] # end # } # end # # # @option options [Symbol,Module] :use The addon or name of an addon to use. # By default, FriendlyId provides {FriendlyId::Slugged :slugged}, # {FriendlyId::Reserved :finders}, {FriendlyId::History :history}, # {FriendlyId::Reserved :reserved}, {FriendlyId::Scoped :scoped}, and # {FriendlyId::SimpleI18n :simple_i18n}. # # @option options [Array] :reserved_words Available when using `:reserved`, # which is loaded by default. Sets an array of words banned for use as # the basis of a friendly_id. By default this includes "edit" and "new". # # @option options [Symbol] :scope Available when using `:scoped`. # Sets the relation or column used to scope generated friendly ids. This # option has no default value. # # @option options [Symbol] :sequence_separator Available when using `:slugged`. # Configures the sequence of characters used to separate a slug from a # sequence. Defaults to `-`. # # @option options [Symbol] :slug_column Available when using `:slugged`. # Configures the name of the column where FriendlyId will store the slug. # Defaults to `:slug`. # # @option options [Integer] :slug_limit Available when using `:slugged`. # Configures the limit of the slug. This option has no default value. # # @option options [Symbol] :slug_generator_class Available when using `:slugged`. # Sets the class used to generate unique slugs. You should not specify this # unless you're doing some extensive hacking on FriendlyId. Defaults to # {FriendlyId::SlugGenerator}. # # @yield Provides access to the model class's friendly_id_config, which # allows an alternate configuration syntax, and conditional configuration # logic. # # @option options [Symbol,Boolean] :dependent Available when using `:history`. # Sets the value used for the slugged association's dependent option. Use # `false` if you do not want to dependently destroy the associated slugged # record. Defaults to `:destroy`. # # @option options [Symbol] :routes When set to anything other than :friendly, # ensures that all routes generated by default do *not* use the slug. This # allows `form_for` and `polymorphic_path` to continue to generate paths like # `/team/1` instead of `/team/number-one`. You can still generate paths # like the latter using: team_path(team.slug). When set to :friendly, or # omitted, the default friendly_id behavior is maintained. # # @yieldparam config The model class's {FriendlyId::Configuration friendly_id_config}. def friendly_id(base = nil, options = {}, &block) yield friendly_id_config if block friendly_id_config.dependent = options.delete :dependent friendly_id_config.use options.delete :use friendly_id_config.send :set, base ? options.merge(base: base) : options include Model end # Returns a scope that includes the friendly finders. # @see FriendlyId::FinderMethods def friendly # Guess what? This causes Rails to invoke `extend` on the scope, which has # the well-known effect of blowing away Ruby's method cache. It would be # possible to make this more performant by subclassing the model's # relation class, extending that, and returning an instance of it in this # method. FriendlyId 4.0 did something similar. However in 5.0 I've # decided to only use Rails's public API in order to improve compatibility # and maintainability. If you'd like to improve the performance, your # efforts would be best directed at improving it at the root cause # of the problem - in Rails - because it would benefit more people. all.extending(friendly_id_config.finder_methods) end # Returns the model class's {FriendlyId::Configuration friendly_id_config}. # @note In the case of Single Table Inheritance (STI), this method will # duplicate the parent class's FriendlyId::Configuration and relation class # on first access. If you're concerned about thread safety, then be sure # to invoke {#friendly_id} in your class for each model. def friendly_id_config @friendly_id_config ||= base_class.friendly_id_config.dup.tap do |config| config.model_class = self end end def primary_key_type @primary_key_type ||= columns_hash[primary_key].type end end # Instance methods that will be added to all classes using FriendlyId. module Model def self.included(model_class) return if model_class.respond_to?(:friendly) end # Convenience method for accessing the class method of the same name. def friendly_id_config self.class.friendly_id_config end # Get the instance's friendly_id. def friendly_id send friendly_id_config.query_field end # Either the friendly_id, or the numeric id cast to a string. def to_param if friendly_id_config.routes == :friendly friendly_id.presence.to_param || super else super end end # Clears slug on duplicate records when calling `dup`. def dup super.tap { |duplicate| duplicate.slug = nil if duplicate.respond_to?("slug=") } end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/configuration.rb
lib/friendly_id/configuration.rb
module FriendlyId # The configuration parameters passed to {Base#friendly_id} will be stored in # this object. class Configuration attr_writer :base # The default configuration options. attr_reader :defaults # The modules in use attr_reader :modules # The model class that this configuration belongs to. # @return ActiveRecord::Base attr_accessor :model_class # The module to use for finders attr_accessor :finder_methods # The value used for the slugged association's dependent option attr_accessor :dependent # Route generation preferences attr_accessor :routes def initialize(model_class, values = nil) @base = nil @model_class = model_class @defaults = {} @modules = [] @finder_methods = FriendlyId::FinderMethods self.routes = :friendly set values end # Lets you specify the addon modules to use with FriendlyId. # # This method is invoked by {FriendlyId::Base#friendly_id friendly_id} when # passing the `:use` option, or when using {FriendlyId::Base#friendly_id # friendly_id} with a block. # # @example # class Book < ActiveRecord::Base # extend FriendlyId # friendly_id :name, :use => :slugged # end # # @param [#to_s,Module] modules Arguments should be Modules, or symbols or # strings that correspond with the name of an addon to use with FriendlyId. # By default FriendlyId provides `:slugged`, `:finders`, `:history`, # `:reserved`, `:simple_i18n`, and `:scoped`. def use(*modules) modules.to_a.flatten.compact.map do |object| mod = get_module(object) mod.setup(@model_class) if mod.respond_to?(:setup) @model_class.send(:include, mod) unless uses? object end end # Returns whether the given module is in use. def uses?(mod) @model_class < get_module(mod) end # The column that FriendlyId will use to find the record when querying by # friendly id. # # This method is generally only used internally by FriendlyId. # @return String def query_field base.to_s end # The base column or method used by FriendlyId as the basis of a friendly id # or slug. # # For models that don't use {FriendlyId::Slugged}, this is the column that # is used to store the friendly id. For models using {FriendlyId::Slugged}, # the base is a column or method whose value is used as the basis of the # slug. # # For example, if you have a model representing blog posts and that uses # slugs, you likely will want to use the "title" attribute as the base, and # FriendlyId will take care of transforming the human-readable title into # something suitable for use in a URL. # # If you pass an argument, it will be used as the base. Otherwise the current # value is returned. # # @param value A symbol referencing a column or method in the model. This # value is usually set by passing it as the first argument to # {FriendlyId::Base#friendly_id friendly_id}. def base(*value) if value.empty? @base else self.base = value.first end end private def get_module(object) Module === object ? object : FriendlyId.const_get(object.to_s.titleize.camelize.gsub(/\s+/, "")) end def set(values) values&.each { |name, value| send "#{name}=", value } end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/finder_methods.rb
lib/friendly_id/finder_methods.rb
module FriendlyId module FinderMethods # Finds a record using the given id. # # If the id is "unfriendly", it will call the original find method. # If the id is a numeric string like '123' it will first look for a friendly # id matching '123' and then fall back to looking for a record with the # numeric id '123'. # # @param [Boolean] allow_nil (default: false) # Use allow_nil: true if you'd like the finder to return nil instead of # raising ActivRecord::RecordNotFound # # ### Example # # MyModel.friendly.find("bad-slug") # #=> raise ActiveRecord::RecordNotFound # # MyModel.friendly.find("bad-slug", allow_nil: true) # #=> nil # # Since FriendlyId 5.0, if the id is a nonnumeric string like '123-foo' it # will *only* search by friendly id and not fall back to the regular find # method. # # If you want to search only by the friendly id, use {#find_by_friendly_id}. # @raise ActiveRecord::RecordNotFound def find(*args, allow_nil: false) id = args.first return super(*args) if args.count != 1 || id.unfriendly_id? first_by_friendly_id(id).tap { |result| return result unless result.nil? } return super(*args) if potential_primary_key?(id) raise_not_found_exception(id) unless allow_nil rescue ActiveRecord::RecordNotFound => exception raise exception unless allow_nil end # Returns true if a record with the given id exists. def exists?(conditions = :none) return super if conditions.unfriendly_id? return true if exists_by_friendly_id?(conditions) super end # Finds exclusively by the friendly id, completely bypassing original # `find`. # @raise ActiveRecord::RecordNotFound def find_by_friendly_id(id) first_by_friendly_id(id) or raise_not_found_exception(id) end def exists_by_friendly_id?(id) where(friendly_id_config.query_field => parse_friendly_id(id)).exists? end private def potential_primary_key?(id) key_type = primary_key_type # Hook for "ActiveModel::Type::Integer" instance. key_type = key_type.type if key_type.respond_to?(:type) case key_type when :integer begin Integer(id, 10) rescue false end when :uuid id.match(/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/) else true end end def first_by_friendly_id(id) find_by(friendly_id_config.query_field => parse_friendly_id(id)) end # Parse the given value to make it suitable for use as a slug according to # your application's rules. # # This method is not intended to be invoked directly; FriendlyId uses it # internally to process a slug into string to use as a finder. # # However, if FriendlyId's default slug parsing doesn't suit your needs, # you can override this method in your model class to control exactly how # slugs are generated. # # ### Example # # class Person < ActiveRecord::Base # extend FriendlyId # friendly_id :name_and_location # # def name_and_location # "#{name} from #{location}" # end # # # Use default slug, but lower case # # If `id` is "Jane-Doe" or "JANE-DOE", this finds data by "jane-doe" # def parse_friendly_id(slug) # super.downcase # end # end # # @param [#to_s] value The slug to be parsed. # @return The parsed slug, which is not modified by default. def parse_friendly_id(value) value end def raise_not_found_exception(id) message = "can't find record with friendly id: #{id.inspect}" if ActiveRecord.version < Gem::Version.create("5.0") raise ActiveRecord::RecordNotFound.new(message) else raise ActiveRecord::RecordNotFound.new(message, name, friendly_id_config.query_field, id) end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/object_utils.rb
lib/friendly_id/object_utils.rb
module FriendlyId # Instances of these classes will never be considered a friendly id. # @see FriendlyId::ObjectUtils#friendly_id UNFRIENDLY_CLASSES = [ Array, FalseClass, Hash, NilClass, Numeric, Symbol, TrueClass ] # Utility methods for determining whether any object is a friendly id. # # Monkey-patching Object is a somewhat extreme measure not to be taken lightly # by libraries, but in this case I decided to do it because to me, it feels # cleaner than adding a module method to {FriendlyId}. I've given the methods # names that unambigously refer to the library of their origin, which should # be sufficient to avoid conflicts with other libraries. module ObjectUtils # True if the id is definitely friendly, false if definitely unfriendly, # else nil. # # An object is considired "definitely unfriendly" if its class is or # inherits from ActiveRecord::Base, Array, Hash, NilClass, Numeric, or # Symbol. # # An object is considered "definitely friendly" if it responds to +to_i+, # and its value when cast to an integer and then back to a string is # different from its value when merely cast to a string: # # 123.friendly_id? #=> false # :id.friendly_id? #=> false # {:name => 'joe'}.friendly_id? #=> false # ['name = ?', 'joe'].friendly_id? #=> false # nil.friendly_id? #=> false # "123".friendly_id? #=> nil # "abc123".friendly_id? #=> true def friendly_id? true if respond_to?(:to_i) && to_i.to_s != to_s end # True if the id is definitely unfriendly, false if definitely friendly, # else nil. def unfriendly_id? val = friendly_id? !val unless val.nil? end end module UnfriendlyUtils def friendly_id? false end def unfriendly_id? true end end def self.mark_as_unfriendly(klass) klass.send(:include, FriendlyId::UnfriendlyUtils) end end Object.send :include, FriendlyId::ObjectUtils # Considered unfriendly if object is an instance of an unfriendly class or # one of its descendants. FriendlyId::UNFRIENDLY_CLASSES.each { |klass| FriendlyId.mark_as_unfriendly(klass) } ActiveSupport.on_load(:active_record) do FriendlyId.mark_as_unfriendly(ActiveRecord::Base) end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/migration.rb
lib/friendly_id/migration.rb
MIGRATION_CLASS = if ActiveRecord::VERSION::MAJOR >= 5 ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"] else ActiveRecord::Migration end class CreateFriendlyIdSlugs < MIGRATION_CLASS def change create_table :friendly_id_slugs do |t| t.string :slug, null: false t.integer :sluggable_id, null: false t.string :sluggable_type, limit: 50 t.string :scope t.datetime :created_at end add_index :friendly_id_slugs, [:sluggable_type, :sluggable_id] add_index :friendly_id_slugs, [:slug, :sluggable_type], length: {slug: 140, sluggable_type: 50} add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], length: {slug: 70, sluggable_type: 50, scope: 70}, unique: true end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/history.rb
lib/friendly_id/history.rb
module FriendlyId # @guide begin # # ## History: Avoiding 404's When Slugs Change # # FriendlyId's {FriendlyId::History History} module adds the ability to store a # log of a model's slugs, so that when its friendly id changes, it's still # possible to perform finds by the old id. # # The primary use case for this is avoiding broken URLs. # # ### Setup # # In order to use this module, you must add a table to your database schema to # store the slug records. FriendlyId provides a generator for this purpose: # # rails generate friendly_id # rake db:migrate # # This will add a table named `friendly_id_slugs`, used by the {FriendlyId::Slug} # model. # # ### Considerations # # Because recording slug history requires creating additional database records, # this module has an impact on the performance of the associated model's `create` # method. # # ### Example # # class Post < ActiveRecord::Base # extend FriendlyId # friendly_id :title, :use => :history # end # # class PostsController < ApplicationController # # before_filter :find_post # # ... # # def find_post # @post = Post.friendly.find params[:id] # # # If an old id or a numeric id was used to find the record, then # # the request slug will not match the current slug, and we should do # # a 301 redirect to the new path # if params[:id] != @post.slug # return redirect_to @post, :status => :moved_permanently # end # end # end # # @guide end module History module Configuration def dependent_value dependent.nil? ? :destroy : dependent end end def self.setup(model_class) model_class.instance_eval do friendly_id_config.use :slugged friendly_id_config.class.send :include, History::Configuration friendly_id_config.finder_methods = FriendlyId::History::FinderMethods FriendlyId::Finders.setup(model_class) if friendly_id_config.uses? :finders end end # Configures the model instance to use the History add-on. def self.included(model_class) model_class.class_eval do has_many :slugs, -> { order(id: :desc) }, **{ as: :sluggable, dependent: @friendly_id_config.dependent_value, class_name: Slug.to_s } after_save :create_slug end end module FinderMethods include ::FriendlyId::FinderMethods def exists_by_friendly_id?(id) super || joins(:slugs).where(slug_history_clause(parse_friendly_id(id))).exists? end private def first_by_friendly_id(id) super || slug_table_record(parse_friendly_id(id)) end def slug_table_record(id) select(quoted_table_name + ".*").joins(:slugs).where(slug_history_clause(id)).order(Slug.arel_table[:id].desc).first end def slug_history_clause(id) Slug.arel_table[:sluggable_type].eq(base_class.to_s).and(Slug.arel_table[:slug].eq(id)) end end private # If we're updating, don't consider historic slugs for the same record # to be conflicts. This will allow a record to revert to a previously # used slug. def scope_for_slug_generator relation = super.joins(:slugs) unless new_record? relation = relation.merge(Slug.where("sluggable_id <> ?", id)) end if friendly_id_config.uses?(:scoped) relation = relation.where(Slug.arel_table[:scope].eq(serialized_scope)) end relation end def create_slug return unless friendly_id return if history_is_up_to_date? # Allow reversion back to a previously used slug relation = slugs.where(slug: friendly_id) if friendly_id_config.uses?(:scoped) relation = relation.where(scope: serialized_scope) end relation.destroy_all unless relation.empty? slugs.create! do |record| record.slug = friendly_id record.scope = serialized_scope if friendly_id_config.uses?(:scoped) end end def history_is_up_to_date? latest_history = slugs.first check = latest_history.try(:slug) == friendly_id if friendly_id_config.uses?(:scoped) check &&= latest_history.scope == serialized_scope end check end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/friendly_id/sequentially_slugged/calculator.rb
lib/friendly_id/sequentially_slugged/calculator.rb
module FriendlyId module SequentiallySlugged class Calculator attr_accessor :scope, :slug, :slug_column, :sequence_separator def initialize(scope, slug, slug_column, sequence_separator, base_class) @scope = scope @slug = slug table_name = scope.connection.quote_table_name(base_class.arel_table.name) @slug_column = "#{table_name}.#{scope.connection.quote_column_name(slug_column)}" @sequence_separator = sequence_separator end def next_slug slug + sequence_separator + next_sequence_number.to_s end private def conflict_query base = "#{slug_column} = ? OR #{slug_column} LIKE ?" # Awful hack for SQLite3, which does not pick up '\' as the escape character # without this. base << " ESCAPE '\\'" if /sqlite/i.match?(scope.connection.adapter_name) base end def next_sequence_number last_sequence_number ? last_sequence_number + 1 : 2 end def last_sequence_number # Reject slug_conflicts that doesn't come from the first_candidate # Map all sequence numbers and take the maximum slug_conflicts .reject { |slug_conflict| !regexp.match(slug_conflict) } .map { |slug_conflict| regexp.match(slug_conflict)[1].to_i } .max end # Return the unnumbered (shortest) slug first, followed by the numbered ones # in ascending order. def ordering_query "#{sql_length}(#{slug_column}) ASC, #{slug_column} ASC" end def regexp /#{slug}#{sequence_separator}(\d+)\z/ end def sequential_slug_matcher # Underscores (matching a single character) and percent signs (matching # any number of characters) need to be escaped. While this looks like # an excessive number of backslashes, it is correct. "#{slug}#{sequence_separator}".gsub(/[_%]/, '\\\\\&') + "%" end def slug_conflicts scope .where(conflict_query, slug, sequential_slug_matcher) .order(Arel.sql(ordering_query)).pluck(Arel.sql(slug_column)) end def sql_length /sqlserver/i.match?(scope.connection.adapter_name) ? "LEN" : "LENGTH" end end end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
norman/friendly_id
https://github.com/norman/friendly_id/blob/f72defb209de742fa51da7aedd1f01687f9e1d4d/lib/generators/friendly_id_generator.rb
lib/generators/friendly_id_generator.rb
require "rails/generators" require "rails/generators/active_record" # This generator adds a migration for the {FriendlyId::History # FriendlyId::History} addon. class FriendlyIdGenerator < ActiveRecord::Generators::Base # ActiveRecord::Generators::Base inherits from Rails::Generators::NamedBase which requires a NAME parameter for the # new table name. Our generator always uses 'friendly_id_slugs', so we just set a random name here. argument :name, type: :string, default: "random_name" class_option :'skip-migration', type: :boolean, desc: "Don't generate a migration for the slugs table" class_option :'skip-initializer', type: :boolean, desc: "Don't generate an initializer" source_root File.expand_path("../../friendly_id", __FILE__) # Copies the migration template to db/migrate. def copy_files return if options["skip-migration"] migration_template "migration.rb", "db/migrate/create_friendly_id_slugs.rb" end def create_initializer return if options["skip-initializer"] copy_file "initializer.rb", "config/initializers/friendly_id.rb" end end
ruby
MIT
f72defb209de742fa51da7aedd1f01687f9e1d4d
2026-01-04T15:40:45.482615Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/features/steps/httparty_steps.rb
features/steps/httparty_steps.rb
When /^I set my HTTParty timeout option to (\d+)$/ do |timeout| @request_options[:timeout] = timeout.to_i end When /^I set my HTTParty open_timeout option to (\d+)$/ do |timeout| @request_options[:open_timeout] = timeout.to_i end When /^I set my HTTParty read_timeout option to (\d+)$/ do |timeout| @request_options[:read_timeout] = timeout.to_i end When /^I set my HTTParty header '(.*)' to value '(.*)'$/ do |name, value| @request_options[:headers] ||= {} @request_options[:headers][name] = value end When /I set my HTTParty logger option/ do # TODO: make the IO something portable @request_options[:logger] = Logger.new("/dev/null") end When /I set my HTTParty parser option to a proc/ do @request_options[:parser] = proc { |body| body } end When /I call HTTParty#get with '(.*)'$/ do |url| begin @response_from_httparty = HTTParty.get("http://#{@host_and_port}#{url}", @request_options) rescue HTTParty::RedirectionTooDeep, Timeout::Error => e @exception_from_httparty = e end end When /^I call HTTParty#head with '(.*)'$/ do |url| begin @response_from_httparty = HTTParty.head("http://#{@host_and_port}#{url}", @request_options) rescue HTTParty::RedirectionTooDeep, Timeout::Error => e @exception_from_httparty = e end end When /I call HTTParty#get with '(.*)' and a basic_auth hash:/ do |url, auth_table| h = auth_table.hashes.first @response_from_httparty = HTTParty.get( "http://#{@host_and_port}#{url}", basic_auth: { username: h["username"], password: h["password"] } ) end When /I call HTTParty#get with '(.*)' and a digest_auth hash:/ do |url, auth_table| h = auth_table.hashes.first @response_from_httparty = HTTParty.get( "http://#{@host_and_port}#{url}", digest_auth: { username: h["username"], password: h["password"] } ) end When /I call Marshal\.dump on the response/ do begin Marshal.dump(@response_from_httparty) rescue TypeError => e @exception_from_httparty = e end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/features/steps/env.rb
features/steps/env.rb
require 'mongrel' require './lib/httparty' require 'rspec/expectations' require 'aruba/cucumber' def run_server(port) @host_and_port = "0.0.0.0:#{port}" @server = Mongrel::HttpServer.new("0.0.0.0", port) @server.run @request_options = {} end def new_port server = TCPServer.new('0.0.0.0', nil) port = server.addr[1] ensure server.close end Before('~@command_line') do port = ENV["HTTPARTY_PORT"] || new_port run_server(port) end After do @server.stop if @server end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/features/steps/mongrel_helper.rb
features/steps/mongrel_helper.rb
require 'base64' class BasicMongrelHandler < Mongrel::HttpHandler attr_accessor :content_type, :custom_headers, :response_body, :response_code, :preprocessor, :username, :password def initialize @content_type = "text/html" @response_body = "" @response_code = 200 @custom_headers = {} end def process(request, response) instance_eval(&preprocessor) if preprocessor reply_with(response, response_code, response_body) end def reply_with(response, code, response_body) response.start(code) do |head, body| head["Content-Type"] = content_type custom_headers.each { |k, v| head[k] = v } body.write(response_body) end end end class DeflateHandler < BasicMongrelHandler def process(request, response) accept_encoding = request.params["HTTP_ACCEPT_ENCODING"] if accept_encoding.nil? || !accept_encoding.include?('deflate') reply_with(response, 406, 'No deflate accept encoding found in request') else response.start do |head, body| require 'zlib' head['Content-Encoding'] = 'deflate' body.write Zlib::Deflate.deflate(response_body) end end end end class GzipHandler < BasicMongrelHandler def process(request, response) accept_encoding = request.params["HTTP_ACCEPT_ENCODING"] if accept_encoding.nil? || !accept_encoding.include?('gzip') reply_with(response, 406, 'No gzip accept encoding found in request') else response.start do |head, body| head['Content-Encoding'] = 'gzip' body.write gzip(response_body) end end end protected def gzip(string) require 'zlib' sio = StringIO.new('', 'r+') gz = Zlib::GzipWriter.new sio gz.write string gz.finish sio.rewind sio.read end end module BasicAuthentication def self.extended(base) base.custom_headers["WWW-Authenticate"] = 'Basic Realm="Super Secret Page"' end def process(request, response) if authorized?(request) super else reply_with(response, 401, "Incorrect. You have 20 seconds to comply.") end end def authorized?(request) request.params["HTTP_AUTHORIZATION"] == "Basic " + Base64.encode64("#{@username}:#{@password}").strip end end module DigestAuthentication def self.extended(base) base.custom_headers["WWW-Authenticate"] = 'Digest realm="testrealm@host.com",qop="auth,auth-int",nonce="nonce",opaque="opaque"' end def process(request, response) if authorized?(request) super else reply_with(response, 401, "Incorrect. You have 20 seconds to comply.") end end def authorized?(request) request.params["HTTP_AUTHORIZATION"] =~ /Digest.*uri=/ end end module DigestAuthenticationUsingMD5Sess NONCE = 'nonce' REALM = 'testrealm@host.com' QOP = 'auth,auth-int' def self.extended(base) base.custom_headers["WWW-Authenticate"] = %(Digest realm="#{REALM}",qop="#{QOP}",algorithm="MD5-sess",nonce="#{NONCE}",opaque="opaque"') end def process(request, response) if authorized?(request) super else reply_with(response, 401, "Incorrect. You have 20 seconds to comply.") end end def md5(str) Digest::MD5.hexdigest(str) end def authorized?(request) auth = request.params["HTTP_AUTHORIZATION"] params = {} auth.to_s.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }.gsub(/(\w+)=([^,]*)/) { params[$1] = $2 } a1a = [@username,REALM,@password].join(':') a1 = [md5(a1a),NONCE,params['cnonce'] ].join(':') a2 = [ request.params["REQUEST_METHOD"], request.params["REQUEST_URI"] ] .join(':') expected_response = md5( [md5(a1), NONCE, params['nc'], params['cnonce'], QOP, md5(a2)].join(':') ) expected_response == params['response'] end end def new_mongrel_redirector(target_url, relative_path = false) target_url = "http://#{@host_and_port}#{target_url}" unless relative_path Mongrel::RedirectHandler.new(target_url) end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/features/steps/httparty_response_steps.rb
features/steps/httparty_response_steps.rb
# Not needed anymore in ruby 2.0, but needed to resolve constants # in nested namespaces. This is taken from rails :) def constantize(camel_cased_word) names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? constant = Object names.each do |name| constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) end constant end Then /it should return an? ([\w\:]+)$/ do |class_string| expect(@response_from_httparty.parsed_response).to be_a(Object.const_get(class_string)) end Then /the return value should match '(.*)'/ do |expected_text| expect(@response_from_httparty.parsed_response).to eq(expected_text) end Then /it should return a Hash equaling:/ do |hash_table| expect(@response_from_httparty.parsed_response).to be_a(Hash) expect(@response_from_httparty.keys.length).to eq(hash_table.rows.length) hash_table.hashes.each do |pair| key, value = pair["key"], pair["value"] expect(@response_from_httparty.keys).to include(key) expect(@response_from_httparty[key]).to eq(value) end end Then /it should return an Array equaling:/ do |array| expect(@response_from_httparty.parsed_response).to be_a(Array) expect(@response_from_httparty.parsed_response).to eq(array.raw) end Then /it should return a response with a (\d+) response code/ do |code| expect(@response_from_httparty.code).to eq(code.to_i) end Then /it should return a response without a content\-encoding$/ do expect(@response_from_httparty.headers['content-encoding']).to be_nil end Then /it should raise (?:an|a) ([\w:]+) exception/ do |exception| expect(@exception_from_httparty).to_not be_nil expect(@exception_from_httparty).to be_a constantize(exception) end Then /it should not raise (?:an|a) ([\w:]+) exception/ do |exception| expect(@exception_from_httparty).to be_nil end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/features/steps/remote_service_steps.rb
features/steps/remote_service_steps.rb
Given /a remote service that returns '(.*)'/ do |response_body| @handler = BasicMongrelHandler.new step "the response from the service has a body of '#{response_body}'" end Given /^a remote service that returns:$/ do |response_body| @handler = BasicMongrelHandler.new @handler.response_body = response_body end Given /a remote service that returns a (\d+) status code/ do |code| @handler = BasicMongrelHandler.new @handler.response_code = code end Given /that service is accessed at the path '(.*)'/ do |path| @server.register(path, @handler) end Given /^that service takes (\d+) (.*) to generate a response$/ do |time, unit| time = time.to_i time *= 60 if unit =~ /minute/ @server_response_time = time @handler.preprocessor = proc { sleep time } end Given /^a remote deflate service$/ do @handler = DeflateHandler.new end Given /^a remote deflate service on port '(\d+)'/ do |port| run_server(port) @handler = DeflateHandler.new end Given /^a remote gzip service$/ do @handler = GzipHandler.new end Given /the response from the service has a Content-Type of '(.*)'/ do |content_type| @handler.content_type = content_type end Given /the response from the service has a body of '(.*)'/ do |response_body| @handler.response_body = response_body end Given /the url '(.*)' redirects to '(.*)'/ do |redirection_url, target_url| @server.register redirection_url, new_mongrel_redirector(target_url) end Given /that service is protected by Basic Authentication/ do @handler.extend BasicAuthentication end Given /that service is protected by Digest Authentication/ do @handler.extend DigestAuthentication end Given /that service is protected by MD5-sess Digest Authentication/ do @handler.extend DigestAuthenticationUsingMD5Sess end Given /that service requires the username '(.*)' with the password '(.*)'/ do |username, password| @handler.username = username @handler.password = password end # customize aruba cucumber step Then /^the output should contain '(.*)'$/ do |expected| expect(all_commands.map(&:output).join("\n")).to match_output_string(expected) end Given /a restricted page at '(.*)'/ do |url| steps " Given a remote service that returns 'A response I will never see' And that service is accessed at the path '#{url}' And that service is protected by Basic Authentication And that service requires the username 'something' with the password 'secret' " end # This joins the server thread, and halts cucumber, so you can actually hit the # server with a browser. Runs until you kill it with Ctrl-c Given /I want to hit this in a browser/ do @server.acceptor.join end Then /I wait for the server to recover/ do timeout = @request_options[:timeout] || 0 sleep @server_response_time - timeout end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty_spec.rb
spec/httparty_spec.rb
require_relative 'spec_helper' RSpec.describe HTTParty do before(:each) do @klass = Class.new @klass.instance_eval { include HTTParty } end describe "pem" do it 'should set the pem content' do @klass.pem 'PEM-CONTENT' expect(@klass.default_options[:pem]).to eq('PEM-CONTENT') end it "should set the password to nil if it's not provided" do @klass.pem 'PEM-CONTENT' expect(@klass.default_options[:pem_password]).to be_nil end it 'should set the password' do @klass.pem 'PEM-CONTENT', 'PASSWORD' expect(@klass.default_options[:pem_password]).to eq('PASSWORD') end end describe "pkcs12" do it 'should set the p12 content' do @klass.pkcs12 'P12-CONTENT', 'PASSWORD' expect(@klass.default_options[:p12]).to eq('P12-CONTENT') end it 'should set the password' do @klass.pkcs12 'P12-CONTENT', 'PASSWORD' expect(@klass.default_options[:p12_password]).to eq('PASSWORD') end end describe 'ssl_version' do it 'should set the ssl_version content' do @klass.ssl_version :SSLv3 expect(@klass.default_options[:ssl_version]).to eq(:SSLv3) end end describe 'ciphers' do it 'should set the ciphers content' do expect(@klass.default_options[:ciphers]).to be_nil @klass.ciphers 'RC4-SHA' expect(@klass.default_options[:ciphers]).to eq('RC4-SHA') end end describe 'http_proxy' do it 'should set the address' do @klass.http_proxy 'proxy.foo.com', 80 options = @klass.default_options expect(options[:http_proxyaddr]).to eq('proxy.foo.com') expect(options[:http_proxyport]).to eq(80) end it 'should set the proxy user and pass when they are provided' do @klass.http_proxy 'proxy.foo.com', 80, 'user', 'pass' options = @klass.default_options expect(options[:http_proxyuser]).to eq('user') expect(options[:http_proxypass]).to eq('pass') end end describe "base uri" do before(:each) do @klass.base_uri('api.foo.com/v1') end it "should have reader" do expect(@klass.base_uri).to eq('http://api.foo.com/v1') end it 'should have writer' do @klass.base_uri('http://api.foobar.com') expect(@klass.base_uri).to eq('http://api.foobar.com') end it 'should not modify the parameter during assignment' do uri = 'http://api.foobar.com' @klass.base_uri(uri) expect(uri).to eq('http://api.foobar.com') end end describe ".disable_rails_query_string_format" do it "sets the query string normalizer to HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER" do @klass.disable_rails_query_string_format expect(@klass.default_options[:query_string_normalizer]).to eq(HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER) end end describe ".normalize_base_uri" do it "should add http if not present for non ssl requests" do uri = HTTParty.normalize_base_uri('api.foobar.com') expect(uri).to eq('http://api.foobar.com') end it "should add https if not present for ssl requests" do uri = HTTParty.normalize_base_uri('api.foo.com/v1:443') expect(uri).to eq('https://api.foo.com/v1:443') end it "should not remove https for ssl requests" do uri = HTTParty.normalize_base_uri('https://api.foo.com/v1:443') expect(uri).to eq('https://api.foo.com/v1:443') end it 'should not modify the parameter' do uri = 'http://api.foobar.com' HTTParty.normalize_base_uri(uri) expect(uri).to eq('http://api.foobar.com') end it "should not treat uri's with a port of 4430 as ssl" do uri = HTTParty.normalize_base_uri('http://api.foo.com:4430/v1') expect(uri).to eq('http://api.foo.com:4430/v1') end end describe "headers" do def expect_headers(header = {}) expect(HTTParty::Request).to receive(:new) \ .with(anything, anything, hash_including({ headers: header })) \ .and_return(double("mock response", perform: nil)) end it "does not modify default_options when no arguments are passed" do @klass.headers expect(@klass.default_options[:headers]).to eq(nil) end it "should default to empty hash" do expect(@klass.headers).to eq({}) end it "should be able to be updated" do init_headers = {foo: 'bar', baz: 'spax'} @klass.headers init_headers expect(@klass.headers).to eq(init_headers) end it "should be able to accept block as header value" do init_headers = {'foo' => lambda {'bar'}} @klass.headers init_headers stub_request(:get, "http://example.com/").with(headers: {'foo' => 'bar', 'baz' => 'spax'}) @klass.get('http://example.com/', headers: {'baz' => -> {'spax'}}) expect(@klass.headers).to eq(init_headers) end it "should pass options as argument to header block value" do init_headers = { 'foo' => lambda { |options| options[:body] } } @klass.headers init_headers stub_request(:get, "http://example.com/").with(body: 'bar', headers: { 'foo' => 'bar', 'baz' => 'rab' }) @klass.get('http://example.com/', body: 'bar',headers: { 'baz' => -> (options){ options[:body].reverse } }) expect(@klass.headers).to eq(init_headers) end it "uses the class headers when sending a request" do expect_headers('foo' => 'bar') @klass.headers(foo: 'bar') @klass.get('') end it "merges class headers with request headers" do expect_headers('baz' => 'spax', 'foo' => 'bar') @klass.headers(foo: 'bar') @klass.get('', headers: {baz: 'spax'}) end it 'overrides class headers with request headers' do expect_headers('baz' => 'spax', 'foo' => 'baz') @klass.headers(foo: 'bar') @klass.get('', headers: {baz: 'spax', foo: 'baz'}) end context "with cookies" do it 'utilizes the class-level cookies' do expect_headers('foo' => 'bar', 'cookie' => 'type=snickerdoodle') @klass.headers(foo: 'bar') @klass.cookies(type: 'snickerdoodle') @klass.get('') end it 'adds cookies to the headers' do expect_headers('foo' => 'bar', 'cookie' => 'type=snickerdoodle') @klass.headers(foo: 'bar') @klass.get('', cookies: {type: 'snickerdoodle'}) end it 'doesnt modify default headers' do expect(@klass.headers).to eq({}) expect_headers('cookie' => 'type=snickerdoodle') @klass.get('', cookies: {type: 'snickerdoodle'}) expect(@klass.headers).to eq({}) end it 'adds optional cookies to the optional headers' do expect_headers('baz' => 'spax', 'cookie' => 'type=snickerdoodle') @klass.get('', cookies: {type: 'snickerdoodle'}, headers: {baz: 'spax'}) end end context 'when posting file' do let(:boundary) { '------------------------c772861a5109d5ef' } let(:headers) do { 'Content-Type'=>"multipart/form-data; boundary=#{boundary}" } end before do expect(HTTParty::Request::MultipartBoundary).to receive(:generate).and_return(boundary) end it 'changes content-type headers to multipart/form-data' do stub_request(:post, "http://example.com/").with(headers: headers) @klass.post('http://example.com', body: { file: File.open('spec/fixtures/tiny.gif')}) end end context 'when headers passed as symbols' do it 'converts them to string' do expect_headers('foo' => 'application/json', 'bar' => 'example') headers = { foo: 'application/json', bar: 'example' } @klass.post('http://example.com', headers: headers) end it 'converts default headers to string' do expect_headers('foo' => 'application/json', 'bar' => 'example') @klass.headers(foo: 'application/json') @klass.post('http://example.com', headers: { bar: 'example' }) end end end describe "cookies" do def expect_cookie_header(s) expect(HTTParty::Request).to receive(:new) \ .with(anything, anything, hash_including({ headers: { "cookie" => s } })) \ .and_return(double("mock response", perform: nil)) end it "should not be in the headers by default" do allow(HTTParty::Request).to receive(:new).and_return(double(nil, perform: nil)) @klass.get("") expect(@klass.headers.keys).not_to include("cookie") end it "should raise an ArgumentError if passed a non-Hash" do expect do @klass.cookies("nonsense") end.to raise_error(ArgumentError) end it "should allow a cookie to be specified with a one-off request" do expect_cookie_header "type=snickerdoodle" @klass.get("", cookies: { type: "snickerdoodle" }) end describe "when a cookie is set at the class level" do before(:each) do @klass.cookies({ type: "snickerdoodle" }) end it "should include that cookie in the request" do expect_cookie_header "type=snickerdoodle" @klass.get("") end it "should pass the proper cookies when requested multiple times" do 2.times do expect_cookie_header "type=snickerdoodle" @klass.get("") end end it "should allow the class defaults to be overridden" do expect_cookie_header "type=chocolate_chip" @klass.get("", cookies: { type: "chocolate_chip" }) end end describe "in a class with multiple methods that use different cookies" do before(:each) do @klass.instance_eval do def first_method get("first_method", cookies: { first_method_cookie: "foo" }) end def second_method get("second_method", cookies: { second_method_cookie: "foo" }) end end end it "should not allow cookies used in one method to carry over into other methods" do expect_cookie_header "first_method_cookie=foo" @klass.first_method expect_cookie_header "second_method_cookie=foo" @klass.second_method end end end describe "default params" do it "should default to empty hash" do expect(@klass.default_params).to eq({}) end it "should be able to be updated" do new_defaults = {foo: 'bar', baz: 'spax'} @klass.default_params new_defaults expect(@klass.default_params).to eq(new_defaults) end end describe "default timeout" do it "should default to nil" do expect(@klass.default_options[:timeout]).to eq(nil) end it "should support updating" do @klass.default_timeout 10 expect(@klass.default_options[:timeout]).to eq(10) end it "should support floats" do @klass.default_timeout 0.5 expect(@klass.default_options[:timeout]).to eq(0.5) end it "should raise an exception if unsupported type provided" do expect { @klass.default_timeout "0.5" }.to raise_error ArgumentError end end describe "debug_output" do it "stores the given stream as a default_option" do @klass.debug_output $stdout expect(@klass.default_options[:debug_output]).to eq($stdout) end it "stores the $stderr stream by default" do @klass.debug_output expect(@klass.default_options[:debug_output]).to eq($stderr) end end describe "basic http authentication" do it "should work" do @klass.basic_auth 'foobar', 'secret' expect(@klass.default_options[:basic_auth]).to eq({username: 'foobar', password: 'secret'}) end end describe "digest http authentication" do it "should work" do @klass.digest_auth 'foobar', 'secret' expect(@klass.default_options[:digest_auth]).to eq({username: 'foobar', password: 'secret'}) end end describe "parser" do class CustomParser def self.parse(body) {sexy: true} end end let(:parser) do proc { |data, format| CustomParser.parse(data) } end it "should set parser options" do @klass.parser parser expect(@klass.default_options[:parser]).to eq(parser) end it "should be able parse response with custom parser" do @klass.parser parser stub_request(:get, 'http://twitter.com/statuses/public_timeline.xml') .to_return(body: 'tweets') custom_parsed_response = @klass.get('http://twitter.com/statuses/public_timeline.xml') expect(custom_parsed_response[:sexy]).to eq(true) end it "raises UnsupportedFormat when the parser cannot handle the format" do @klass.format :json parser_class = Class.new(HTTParty::Parser) parser_class::SupportedFormats = {} expect do @klass.parser parser_class end.to raise_error(HTTParty::UnsupportedFormat) end it 'does not validate format whe custom parser is a proc' do expect do @klass.format :json @klass.parser lambda {|body, format|} end.to_not raise_error end end describe "uri_adapter" do context 'with Addressable::URI' do before do @klass.uri_adapter(Addressable::URI) end it 'handles international domains' do uri = 'http://xn--i-7iqv272g.ws/' stub_request(:get, uri).to_return(body: 'stuff') response = @klass.get('http://i❤️.ws') expect(response.parsed_response).to eq('stuff') expect(response.request.uri.to_s).to eq(uri) end end context 'with custom URI Adaptor' do require 'forwardable' class CustomURIAdaptor extend Forwardable def_delegators :@uri, :userinfo, :relative?, :query, :query=, :scheme, :path, :host, :port def initialize(uri) @uri = uri end def self.parse(uri) new(URI.parse(uri)) end def normalize self end end let(:uri_adapter) { CustomURIAdaptor } it "should set the uri_adapter" do @klass.uri_adapter uri_adapter expect(@klass.default_options[:uri_adapter]).to be uri_adapter end it "should raise an ArgumentError if uri_adapter doesn't implement parse method" do expect do @klass.uri_adapter double() end.to raise_error(ArgumentError) end it "should process a request with a uri instance parsed from the uri_adapter" do uri = 'http://foo.com/bar' stub_request(:get, uri).to_return(body: 'stuff') @klass.uri_adapter uri_adapter expect(@klass.get(uri).parsed_response).to eq('stuff') end end end describe "connection_adapter" do let(:uri) { 'http://google.com/api.json' } let(:connection_adapter) { double('CustomConnectionAdapter') } it "should set the connection_adapter" do @klass.connection_adapter connection_adapter expect(@klass.default_options[:connection_adapter]).to be connection_adapter end it "should set the connection_adapter_options when provided" do options = {foo: :bar} @klass.connection_adapter connection_adapter, options expect(@klass.default_options[:connection_adapter_options]).to be options end it "should not set the connection_adapter_options when not provided" do @klass.connection_adapter connection_adapter expect(@klass.default_options[:connection_adapter_options]).to be_nil end it "should process a request with a connection from the adapter" do connection_adapter_options = {foo: :bar} expect(connection_adapter).to receive(:call) { |u, o| expect(o[:connection_adapter_options]).to eq(connection_adapter_options) HTTParty::ConnectionAdapter.call(u, o) }.with(URI.parse(uri), kind_of(Hash)) stub_request(:get, uri).to_return(body: 'stuff') @klass.connection_adapter connection_adapter, connection_adapter_options expect(@klass.get(uri).parsed_response).to eq('stuff') end end describe "format" do it "should allow xml" do @klass.format :xml expect(@klass.default_options[:format]).to eq(:xml) end it "should allow csv" do @klass.format :csv expect(@klass.default_options[:format]).to eq(:csv) end it "should allow json" do @klass.format :json expect(@klass.default_options[:format]).to eq(:json) end it "should allow plain" do @klass.format :plain expect(@klass.default_options[:format]).to eq(:plain) end it 'should not allow funky format' do expect do @klass.format :foobar end.to raise_error(HTTParty::UnsupportedFormat) end it 'should only print each format once with an exception' do expect do @klass.format :foobar end.to raise_error(HTTParty::UnsupportedFormat, "':foobar' Must be one of: csv, html, json, plain, xml") end it 'sets the default parser' do expect(@klass.default_options[:parser]).to be_nil @klass.format :json expect(@klass.default_options[:parser]).to eq(HTTParty::Parser) end it 'does not reset parser to the default parser' do my_parser = lambda {} @klass.parser my_parser @klass.format :json expect(@klass.parser).to eq(my_parser) end end describe "#no_follow" do it "sets no_follow to false by default" do @klass.no_follow expect(@klass.default_options[:no_follow]).to be_falsey end it "sets the no_follow option to true" do @klass.no_follow true expect(@klass.default_options[:no_follow]).to be_truthy end end describe "#maintain_method_across_redirects" do it "sets maintain_method_across_redirects to true by default" do @klass.maintain_method_across_redirects expect(@klass.default_options[:maintain_method_across_redirects]).to be_truthy end it "sets the maintain_method_across_redirects option to false" do @klass.maintain_method_across_redirects false expect(@klass.default_options[:maintain_method_across_redirects]).to be_falsey end end describe "#resend_on_redirect" do it "sets resend_on_redirect to true by default" do @klass.resend_on_redirect expect(@klass.default_options[:resend_on_redirect]).to be_truthy end it "sets resend_on_redirect option to false" do @klass.resend_on_redirect false expect(@klass.default_options[:resend_on_redirect]).to be_falsey end end describe ".follow_redirects" do it "sets follow redirects to true by default" do @klass.follow_redirects expect(@klass.default_options[:follow_redirects]).to be_truthy end it "sets the follow_redirects option to false" do @klass.follow_redirects false expect(@klass.default_options[:follow_redirects]).to be_falsey end end describe ".query_string_normalizer" do it "sets the query_string_normalizer option" do normalizer = proc {} @klass.query_string_normalizer normalizer expect(@klass.default_options[:query_string_normalizer]).to eq(normalizer) end end describe ".raise_on" do context 'when parameters is an array' do it 'sets raise_on option' do @klass.raise_on [500, 404] expect(@klass.default_options[:raise_on]).to contain_exactly(404, 500) end end context 'when parameters is a fixnum' do it 'sets raise_on option' do @klass.raise_on 404 expect(@klass.default_options[:raise_on]).to contain_exactly(404) end end end describe "with explicit override of automatic redirect handling" do before do @request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml, no_follow: true) @redirect = stub_response 'first redirect', 302 @redirect['location'] = 'http://foo.com/bar' allow(HTTParty::Request).to receive_messages(new: @request) end it "should fail with redirected GET" do expect do @error = @klass.get('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected POST" do expect do @klass.post('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected PATCH" do expect do @klass.patch('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected DELETE" do expect do @klass.delete('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected MOVE" do expect do @klass.move('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected COPY" do expect do @klass.copy('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected PUT" do expect do @klass.put('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected HEAD" do expect do @klass.head('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected OPTIONS" do expect do @klass.options('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end it "should fail with redirected MKCOL" do expect do @klass.mkcol('/foo', no_follow: true) end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')} end end describe "head requests should follow redirects requesting HEAD only" do before do allow(HTTParty::Request).to receive(:new). and_return(double("mock response", perform: nil)) end it "should remain HEAD request across redirects, unless specified otherwise" do expect(@klass).to receive(:ensure_method_maintained_across_redirects).with({}) @klass.head('/foo') end end describe "#ensure_method_maintained_across_redirects" do it "should set maintain_method_across_redirects option if unspecified" do options = {} @klass.send(:ensure_method_maintained_across_redirects, options) expect(options[:maintain_method_across_redirects]).to be_truthy end it "should not set maintain_method_across_redirects option if value is present" do options = { maintain_method_across_redirects: false } @klass.send(:ensure_method_maintained_across_redirects, options) expect(options[:maintain_method_across_redirects]).to be_falsey end end describe "with multiple class definitions" do before(:each) do @klass.instance_eval do base_uri "http://first.com" default_params one: 1 end @additional_klass = Class.new @additional_klass.instance_eval do include HTTParty base_uri "http://second.com" default_params two: 2 end end it "should not run over each others options" do expect(@klass.default_options).to eq({ base_uri: 'http://first.com', default_params: { one: 1 } }) expect(@additional_klass.default_options).to eq({ base_uri: 'http://second.com', default_params: { two: 2 } }) end end describe "two child classes inheriting from one parent" do before(:each) do @parent = Class.new do include HTTParty def self.name "Parent" end end @child1 = Class.new(@parent) @child2 = Class.new(@parent) end it "does not modify each others inherited attributes" do @child1.default_params joe: "alive" @child2.default_params joe: "dead" expect(@child1.default_options).to eq({ default_params: {joe: "alive"} }) expect(@child2.default_options).to eq({ default_params: {joe: "dead"} }) expect(@parent.default_options).to eq({ }) end it "inherits default_options from the superclass" do @parent.basic_auth 'user', 'password' expect(@child1.default_options).to eq({basic_auth: {username: 'user', password: 'password'}}) @child1.basic_auth 'u', 'p' # modifying child1 has no effect on child2 expect(@child2.default_options).to eq({basic_auth: {username: 'user', password: 'password'}}) end it "doesn't modify the parent's default options" do @parent.basic_auth 'user', 'password' @child1.basic_auth 'u', 'p' expect(@child1.default_options).to eq({basic_auth: {username: 'u', password: 'p'}}) @child1.basic_auth 'email', 'token' expect(@child1.default_options).to eq({basic_auth: {username: 'email', password: 'token'}}) expect(@parent.default_options).to eq({basic_auth: {username: 'user', password: 'password'}}) end it "doesn't modify hashes in the parent's default options" do @parent.headers 'Accept' => 'application/json' @child1.headers 'Accept' => 'application/xml' expect(@parent.default_options[:headers]).to eq({'Accept' => 'application/json'}) expect(@child1.default_options[:headers]).to eq({'Accept' => 'application/xml'}) end it "works with lambda values" do @child1.default_options[:imaginary_option] = lambda { "This is a new lambda "} expect(@child1.default_options[:imaginary_option]).to be_a Proc end it 'should dup the proc on the child class' do imaginary_option = lambda { 2 * 3.14 } @parent.default_options[:imaginary_option] = imaginary_option expect(@parent.default_options[:imaginary_option].call).to eq(imaginary_option.call) @child1.default_options[:imaginary_option] expect(@child1.default_options[:imaginary_option].call).to eq(imaginary_option.call) expect(@child1.default_options[:imaginary_option]).not_to be_equal imaginary_option end it "inherits default_cookies from the parent class" do @parent.cookies 'type' => 'chocolate_chip' expect(@child1.default_cookies).to eq({"type" => "chocolate_chip"}) @child1.cookies 'type' => 'snickerdoodle' expect(@child1.default_cookies).to eq({"type" => "snickerdoodle"}) expect(@child2.default_cookies).to eq({"type" => "chocolate_chip"}) end it "doesn't modify the parent's default cookies" do @parent.cookies 'type' => 'chocolate_chip' @child1.cookies 'type' => 'snickerdoodle' expect(@child1.default_cookies).to eq({"type" => "snickerdoodle"}) expect(@parent.default_cookies).to eq({"type" => "chocolate_chip"}) end end describe "grand parent with inherited callback" do before do @grand_parent = Class.new do def self.inherited(subclass) subclass.instance_variable_set(:@grand_parent, true) end end @parent = Class.new(@grand_parent) do include HTTParty end end it "continues running the #inherited on the parent" do child = Class.new(@parent) expect(child.instance_variable_get(:@grand_parent)).to be_truthy end end describe "#get" do it "should be able to get html" do stub_http_response_with('example.html') expect(HTTParty.get('http://www.example.com').parsed_response).to eq(file_fixture('example.html')) end it "should be able to get chunked html" do chunks = %w(Chunk1 Chunk2 Chunk3 Chunk4) stub_chunked_http_response_with(chunks) expect( HTTParty.get('http://www.google.com') do |fragment| expect(chunks).to include(fragment) end.parsed_response ).to eq(chunks.join) end it "should return an empty body if stream_body option is turned on" do chunks = %w(Chunk1 Chunk2 Chunk3 Chunk4) options = {stream_body: true, format: 'html'} stub_chunked_http_response_with(chunks, options) expect( HTTParty.get('http://www.google.com', options) do |fragment| expect(chunks).to include(fragment) expect(fragment.code).to eql 200 expect(fragment.http_response).to be end.parsed_response ).to eq(nil) end context 'when streaming body' do let(:chunk) { 'Content'.force_encoding('ascii-8bit') } let(:options) { { stream_body: true } } before do stub_chunked_http_response_with([chunk], options) do |response| allow(response).to receive(:[]).with('content-type').and_return('text/plain; charset = "utf-8"') allow(response).to receive(:[]).with('content-encoding').and_return(nil) end end specify do HTTParty.get('http://www.google.com', options) do |fragment| expect(fragment.encoding).to eq(Encoding.find("UTF-8")) end end end it "should be able parse response type json automatically" do stub_http_response_with('twitter.json') tweets = HTTParty.get('http://twitter.com/statuses/public_timeline.json') expect(tweets.size).to eq(20) expect(tweets.first['user']).to eq({ "name" => "Pyk", "url" => nil, "id" => "7694602", "description" => nil, "protected" => false, "screen_name" => "Pyk", "followers_count" => 1, "location" => "Opera Plaza, California", "profile_image_url" => "http://static.twitter.com/images/default_profile_normal.png" }) end it "should be able parse response type xml automatically" do stub_http_response_with('twitter.xml') tweets = HTTParty.get('http://twitter.com/statuses/public_timeline.xml') expect(tweets['statuses'].size).to eq(20) expect(tweets['statuses'].first['user']).to eq({ "name" => "Magic 8 Bot", "url" => nil, "id" => "17656026", "description" => "ask me a question", "protected" => "false", "screen_name" => "magic8bot", "followers_count" => "90", "profile_image_url" => "http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg", "location" => nil }) end it "should be able parse response type csv automatically" do stub_http_response_with('twitter.csv') profile = HTTParty.get('http://twitter.com/statuses/profile.csv') expect(profile.size).to eq(2) expect(profile[0]).to eq(%w(name url id description protected screen_name followers_count profile_image_url location)) expect(profile[1]).to eq(["Magic 8 Bot", nil, "17656026", "ask me a question", "false", "magic8bot", "90", "http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg", nil]) end it "should not get undefined method add_node for nil class for the following xml" do stub_http_response_with('undefined_method_add_node_for_nil.xml') result = HTTParty.get('http://foobar.com') expect(result.parsed_response).to eq({"Entities" => {"href" => "https://s3-sandbox.parature.com/api/v1/5578/5633/Account", "results" => "0", "total" => "0", "page_size" => "25", "page" => "1"}}) end it "should parse empty response fine" do stub_http_response_with('empty.xml') result = HTTParty.get('http://foobar.com') expect(result).to be_nil end it "should accept http URIs" do stub_http_response_with('example.html') expect do HTTParty.get('http://example.com') end.not_to raise_error end it "should accept https URIs" do stub_http_response_with('example.html') expect do HTTParty.get('https://example.com') end.not_to raise_error end it "should accept webcal URIs" do uri = 'http://google.com/' stub_request(:get, uri).to_return(body: 'stuff') uri = 'webcal://google.com/' expect do HTTParty.get(uri) end.not_to raise_error end it "should raise an InvalidURIError on URIs that can't be parsed at all" do expect do HTTParty.get("It's the one that says 'Bad URI'") end.to raise_error(URI::InvalidURIError) end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
true
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/spec_helper.rb
spec/spec_helper.rb
require "simplecov" SimpleCov.start require "httparty" require 'webmock/rspec' def file_fixture(filename) open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename}")).read end Dir[File.expand_path(File.join(File.dirname(__FILE__), 'support', '**', '*.rb'))].each {|f| require f} RSpec.configure do |config| config.include HTTParty::StubResponse config.include HTTParty::SSLTestHelper config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = false end config.filter_run :focus config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random config.before(:each) do # Reset default_cert_store cache HTTParty::ConnectionAdapter.instance_variable_set(:@default_cert_store, nil) end Kernel.srand config.seed end RSpec::Matchers.define :use_ssl do match(&:use_ssl?) end RSpec::Matchers.define :use_cert_store do |cert_store| match do |connection| connection.cert_store == cert_store end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/support/ssl_test_helper.rb
spec/support/ssl_test_helper.rb
require 'pathname' module HTTParty module SSLTestHelper def ssl_verify_test(mode, ca_basename, server_cert_filename, options = {}, &block) options = { format: :json, timeout: 30 }.merge(options) if mode ca_path = File.expand_path("../../fixtures/ssl/generated/#{ca_basename}", __FILE__) raise ArgumentError.new("#{ca_path} does not exist") unless File.exist?(ca_path) options[mode] = ca_path end begin test_server = SSLTestServer.new( rsa_key: File.read(File.expand_path("../../fixtures/ssl/generated/server.key", __FILE__)), cert: File.read(File.expand_path("../../fixtures/ssl/generated/#{server_cert_filename}", __FILE__))) test_server.start if mode ca_path = File.expand_path("../../fixtures/ssl/generated/#{ca_basename}", __FILE__) raise ArgumentError.new("#{ca_path} does not exist") unless File.exist?(ca_path) return HTTParty.get("https://localhost:#{test_server.port}/", options, &block) else return HTTParty.get("https://localhost:#{test_server.port}/", options, &block) end ensure test_server.stop if test_server end test_server = SSLTestServer.new({ rsa_key: path.join('server.key').read, cert: path.join(server_cert_filename).read }) test_server.start HTTParty.get("https://localhost:#{test_server.port}/", options, &block) ensure test_server.stop if test_server end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/support/stub_response.rb
spec/support/stub_response.rb
module HTTParty module StubResponse def stub_http_response_with(filename) format = filename.split('.').last.intern data = file_fixture(filename) response = Net::HTTPOK.new("1.1", 200, "Content for you") allow(response).to receive(:body).and_return(data) http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', format: format) allow(http_request).to receive_message_chain(:http, :request).and_return(response) expect(HTTParty::Request).to receive(:new).and_return(http_request) end def stub_chunked_http_response_with(chunks, options = {format: "html"}) response = Net::HTTPResponse.new("1.1", 200, nil) allow(response).to receive(:chunked_data).and_return(chunks) def response.read_body(&block) @body || chunked_data.each(&block) end yield(response) if block_given? http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', options) allow(http_request).to receive_message_chain(:http, :request).and_yield(response).and_return(response) expect(HTTParty::Request).to receive(:new).and_return(http_request) end def stub_response(body, code = '200') code = code.to_s # Only set default base_uri if path is relative (has no host) # This avoids triggering URI safety validation for absolute URLs in tests @request.options[:base_uri] ||= 'http://localhost' if @request.path.relative? unless defined?(@http) && @http @http = Net::HTTP.new('localhost', 80) allow(@request).to receive(:http).and_return(@http) end # CODE_TO_OBJ currently missing 308 if code == '308' response = Net::HTTPRedirection.new("1.1", code, body) else response = Net::HTTPResponse::CODE_TO_OBJ[code].new("1.1", code, body) end allow(response).to receive(:body).and_return(body) allow(@http).to receive(:request).and_return(response) response end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/support/ssl_test_server.rb
spec/support/ssl_test_server.rb
require 'openssl' require 'socket' require 'thread' # NOTE: This code is garbage. It probably has deadlocks, it might leak # threads, and otherwise cause problems in a real system. It's really only # intended for testing HTTParty. class SSLTestServer attr_accessor :ctx # SSLContext object attr_reader :port def initialize(options = {}) @ctx = OpenSSL::SSL::SSLContext.new @ctx.cert = OpenSSL::X509::Certificate.new(options[:cert]) @ctx.key = OpenSSL::PKey::RSA.new(options[:rsa_key]) @ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # Don't verify client certificate @port = options[:port] || 0 @thread = nil @stopping_mutex = Mutex.new @stopping = false end def start @raw_server = TCPServer.new(@port) if @port == 0 @port = Socket.getnameinfo(@raw_server.getsockname, Socket::NI_NUMERICHOST | Socket::NI_NUMERICSERV)[1].to_i end @ssl_server = OpenSSL::SSL::SSLServer.new(@raw_server, @ctx) @stopping_mutex.synchronize { return if @stopping @thread = Thread.new { thread_main } } nil end def stop @stopping_mutex.synchronize { return if @stopping @stopping = true } @thread.join end private def thread_main until @stopping_mutex.synchronize { @stopping } (rr, _, _) = select([@ssl_server.to_io], nil, nil, 0.1) next unless rr && rr.include?(@ssl_server.to_io) socket = @ssl_server.accept Thread.new { header = [] until (line = socket.readline).rstrip.empty? header << line end response = <<EOF HTTP/1.1 200 OK Connection: close Content-Type: application/json; charset=UTF-8 {"success":true} EOF socket.write(response.gsub(/\r\n/n, "\n").gsub(/\n/n, "\r\n")) socket.close } end @ssl_server.close end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/response_spec.rb
spec/httparty/response_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Response do before do @last_modified = Date.new(2010, 1, 15).to_s @content_length = '1024' @request_object = HTTParty::Request.new Net::HTTP::Get, '/' @response_object = Net::HTTPOK.new('1.1', 200, 'OK') allow(@response_object).to receive_messages(body: "{foo:'bar'}") @response_object['last-modified'] = @last_modified @response_object['content-length'] = @content_length @parsed_response = lambda { {"foo" => "bar"} } @response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) end describe ".underscore" do it "works with one capitalized word" do expect(HTTParty::Response.underscore("Accepted")).to eq("accepted") end it "works with titlecase" do expect(HTTParty::Response.underscore("BadGateway")).to eq("bad_gateway") end it "works with all caps" do expect(HTTParty::Response.underscore("OK")).to eq("ok") end end describe "initialization" do it "should set the Net::HTTP Response" do expect(@response.response).to eq(@response_object) end it "should set body" do expect(@response.body).to eq(@response_object.body) end it "should set code" do expect(@response.code).to eq(@response_object.code) end it "should set code as an Integer" do expect(@response.code).to be_a(Integer) end it "should set http_version" do unparseable_body = lambda { raise "Unparseable" } unparseable_response = HTTParty::Response.new(@request_object, @response_object, unparseable_body) expect(unparseable_response.http_version).to eq(@response_object.http_version) end context 'test raise_on requests' do let(:raise_on) { [404] } let(:request) { HTTParty::Request.new(Net::HTTP::Get, '/', raise_on: raise_on) } let(:body) { 'Not Found' } let(:response) { Net::HTTPNotFound.new('1.1', 404, body) } subject { described_class.new(request, response, @parsed_response) } before do allow(response).to receive(:body).and_return(body) end context 'when raise_on is a number' do let(:raise_on) { [404] } context "and response's status code is in range" do it 'throws exception' do expect{ subject }.to raise_error(HTTParty::ResponseError, "Code 404 - #{body}") end end context "and response's status code is not in range" do let(:response) { Net::HTTPNotFound.new('1.1', 200, body) } it 'does not throw exception' do expect{ subject }.not_to raise_error end end end context 'when raise_on is a regexpr' do let(:raise_on) { ['4[0-9]*'] } context "and response's status code is in range" do it 'throws exception' do expect{ subject }.to raise_error(HTTParty::ResponseError, "Code 404 - #{body}") end end context "and response's status code is not in range" do let(:response) { Net::HTTPNotFound.new('1.1', 200, body) } it 'does not throw exception' do expect{ subject }.not_to raise_error end end end end end it 'does raise an error about itself when using #method' do expect { HTTParty::Response.new(@request_object, @response_object, @parsed_response).method(:qux) }.to raise_error(NameError, /HTTParty\:\:Response/) end it 'does raise an error about itself when invoking a method that does not exist' do expect { HTTParty::Response.new(@request_object, @response_object, @parsed_response).qux }.to raise_error(NoMethodError, /HTTParty\:\:Response/) end it "returns response headers" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.headers).to eq({'last-modified' => [@last_modified], 'content-length' => [@content_length]}) end it "should send missing methods to delegate" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response['foo']).to eq('bar') end it "responds to request" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:request)).to be_truthy end it "responds to response" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:response)).to be_truthy end it "responds to body" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:body)).to be_truthy end it "responds to headers" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:headers)).to be_truthy end it "responds to parsed_response" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:parsed_response)).to be_truthy end it "responds to predicates" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:success?)).to be_truthy end it "responds to anything parsed_response responds to" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.respond_to?(:[])).to be_truthy end context 'response is array' do let(:response_value) { [{'foo' => 'bar'}, {'foo' => 'baz'}] } let(:response) { HTTParty::Response.new(@request_object, @response_object, lambda { response_value }) } it "should be able to iterate" do expect(response.size).to eq(2) expect { response.each { |item| } }.to_not raise_error end it 'should respond to array methods' do expect(response).to respond_to(:bsearch, :compact, :cycle, :delete, :each, :flatten, :flatten!, :compact, :join) end it 'should equal the string response object body' do expect(response.to_s).to eq(@response_object.body.to_s) end it 'should display the same as an array' do a = StringIO.new b = StringIO.new response_value.display(b) response.display(a) expect(a.string).to eq(b.string) end end it "allows headers to be accessed by mixed-case names in hash notation" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.headers['Content-LENGTH']).to eq(@content_length) end it "returns a comma-delimited value when multiple values exist" do @response_object.add_field 'set-cookie', 'csrf_id=12345; path=/' @response_object.add_field 'set-cookie', '_github_ses=A123CdE; path=/' response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) expect(response.headers['set-cookie']).to eq("csrf_id=12345; path=/, _github_ses=A123CdE; path=/") end # Backwards-compatibility - previously, #headers returned a Hash it "responds to hash methods" do response = HTTParty::Response.new(@request_object, @response_object, @parsed_response) hash_methods = {}.methods - response.headers.methods hash_methods.each do |method_name| expect(response.headers.respond_to?(method_name)).to be_truthy end end describe "#is_a?" do subject { HTTParty::Response.new(@request_object, @response_object, @parsed_response) } it { is_expected.to respond_to(:is_a?).with(1).arguments } it { expect(subject.is_a?(HTTParty::Response)).to be_truthy } it { expect(subject.is_a?(Object)).to be_truthy } end describe "#kind_of?" do subject { HTTParty::Response.new(@request_object, @response_object, @parsed_response) } it { is_expected.to respond_to(:kind_of?).with(1).arguments } it { expect(subject.kind_of?(HTTParty::Response)).to be_truthy } it { expect(subject.kind_of?(Object)).to be_truthy } end describe "semantic methods for response codes" do def response_mock(klass) response = klass.new('', '', '') allow(response).to receive(:body) response end context "major codes" do it "is information" do net_response = response_mock(Net::HTTPInformation) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.information?).to be_truthy end it "is success" do net_response = response_mock(Net::HTTPSuccess) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.success?).to be_truthy end it "is redirection" do net_response = response_mock(Net::HTTPRedirection) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.redirection?).to be_truthy end it "is client error" do net_response = response_mock(Net::HTTPClientError) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.client_error?).to be_truthy end it "is server error" do net_response = response_mock(Net::HTTPServerError) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.server_error?).to be_truthy end end context "for specific codes" do SPECIFIC_CODES = { accepted?: Net::HTTPAccepted, bad_gateway?: Net::HTTPBadGateway, bad_request?: Net::HTTPBadRequest, conflict?: Net::HTTPConflict, continue?: Net::HTTPContinue, created?: Net::HTTPCreated, expectation_failed?: Net::HTTPExpectationFailed, forbidden?: Net::HTTPForbidden, found?: Net::HTTPFound, gateway_time_out?: Net::HTTPGatewayTimeOut, gone?: Net::HTTPGone, internal_server_error?: Net::HTTPInternalServerError, length_required?: Net::HTTPLengthRequired, method_not_allowed?: Net::HTTPMethodNotAllowed, moved_permanently?: Net::HTTPMovedPermanently, multiple_choice?: Net::HTTPMultipleChoice, no_content?: Net::HTTPNoContent, non_authoritative_information?: Net::HTTPNonAuthoritativeInformation, not_acceptable?: Net::HTTPNotAcceptable, not_found?: Net::HTTPNotFound, not_implemented?: Net::HTTPNotImplemented, not_modified?: Net::HTTPNotModified, ok?: Net::HTTPOK, partial_content?: Net::HTTPPartialContent, payment_required?: Net::HTTPPaymentRequired, precondition_failed?: Net::HTTPPreconditionFailed, proxy_authentication_required?: Net::HTTPProxyAuthenticationRequired, request_entity_too_large?: Net::HTTPRequestEntityTooLarge, request_time_out?: Net::HTTPRequestTimeOut, request_uri_too_long?: Net::HTTPRequestURITooLong, requested_range_not_satisfiable?: Net::HTTPRequestedRangeNotSatisfiable, reset_content?: Net::HTTPResetContent, see_other?: Net::HTTPSeeOther, service_unavailable?: Net::HTTPServiceUnavailable, switch_protocol?: Net::HTTPSwitchProtocol, temporary_redirect?: Net::HTTPTemporaryRedirect, unauthorized?: Net::HTTPUnauthorized, unsupported_media_type?: Net::HTTPUnsupportedMediaType, use_proxy?: Net::HTTPUseProxy, version_not_supported?: Net::HTTPVersionNotSupported } if ::RUBY_PLATFORM != "java" SPECIFIC_CODES[:multiple_choices?] = Net::HTTPMultipleChoices end # Ruby 2.6, those status codes have been updated. if ::RUBY_PLATFORM != "java" SPECIFIC_CODES[:gateway_timeout?] = Net::HTTPGatewayTimeout SPECIFIC_CODES[:payload_too_large?] = Net::HTTPPayloadTooLarge SPECIFIC_CODES[:request_timeout?] = Net::HTTPRequestTimeout SPECIFIC_CODES[:uri_too_long?] = Net::HTTPURITooLong SPECIFIC_CODES[:range_not_satisfiable?] = Net::HTTPRangeNotSatisfiable end SPECIFIC_CODES.each do |method, klass| it "responds to #{method}" do net_response = response_mock(klass) response = HTTParty::Response.new(@request_object, net_response, '') expect(response.__send__(method)).to be_truthy end end end end describe "headers" do let (:empty_headers) { HTTParty::Response::Headers.new } let (:some_headers_hash) do {'Cookie' => 'bob', 'Content-Encoding' => 'meow'} end let (:some_headers) do HTTParty::Response::Headers.new.tap do |h| some_headers_hash.each_pair do |k,v| h[k] = v end end end it "can initialize without headers" do expect(empty_headers).to eq({}) end it 'always equals itself' do expect(empty_headers).to eq(empty_headers) expect(some_headers).to eq(some_headers) end it 'does not equal itself when not equivalent' do expect(empty_headers).to_not eq(some_headers) end it 'does equal a hash' do expect(empty_headers).to eq({}) expect(some_headers).to eq(some_headers_hash) end end describe "#tap" do it "is possible to tap into a response" do result = @response.tap(&:code) expect(result).to eq @response end end describe "#inspect" do it "works" do inspect = @response.inspect expect(inspect).to include("HTTParty::Response:0x") expect(inspect).to match(/parsed_response=.*\{.*foo.*=>.*bar.*\}/) expect(inspect).to include("@response=#<Net::HTTPOK 200 OK readbody=false>") expect(inspect).to include("@headers={") expect(inspect).to include("last-modified") expect(inspect).to include("content-length") end end describe 'marshalling' do before { RSpec::Mocks.space.proxy_for(@response_object).remove_stub(:body) } specify do marshalled = Marshal.load(Marshal.dump(@response)) expect(marshalled.headers).to eq @response.headers expect(marshalled.body).to eq @response.body expect(marshalled.code).to eq @response.code end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/headers_processor_spec.rb
spec/httparty/headers_processor_spec.rb
require 'spec_helper' RSpec.describe HTTParty::HeadersProcessor do subject(:headers) { options[:headers] } let(:options) { { headers: {} } } let(:global_headers) { {} } before { described_class.new(global_headers, options).call } context 'when headers are not set at all' do it 'returns empty hash' do expect(headers).to eq({}) end end context 'when only global headers are set' do let(:global_headers) { { accept: 'text/html' } } it 'returns stringified global headers' do expect(headers).to eq('accept' => 'text/html') end end context 'when only request specific headers are set' do let(:options) { { headers: {accept: 'text/html' } } } it 'returns stringified request specific headers' do expect(headers).to eq('accept' => 'text/html') end end context 'when global and request specific headers are set' do let(:global_headers) { { 'x-version' => '123' } } let(:options) { { headers: { accept: 'text/html' } } } it 'returns merged global and request specific headers' do expect(headers).to eq('accept' => 'text/html', 'x-version' => '123') end end context 'when headers are dynamic' do let(:global_headers) { {'x-version' => -> { 'abc'.reverse } } } let(:options) do { body: '123', headers: { sum: lambda { |options| options[:body].chars.map(&:to_i).inject(:+) } } } end it 'returns processed global and request specific headers' do expect(headers).to eq('sum' => 6, 'x-version' => 'cba') end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/exception_spec.rb
spec/httparty/exception_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Error do subject { described_class } describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(StandardError) } end describe HTTParty::UnsupportedFormat do describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(HTTParty::Error) } end end describe HTTParty::UnsupportedURIScheme do describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(HTTParty::Error) } end end describe HTTParty::ResponseError do describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(HTTParty::Error) } end end describe HTTParty::RedirectionTooDeep do describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(HTTParty::ResponseError) } end end describe HTTParty::DuplicateLocationHeader do describe '#ancestors' do subject { super().ancestors } it { is_expected.to include(HTTParty::ResponseError) } end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/request_spec.rb
spec/httparty/request_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Request do before do @request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml) end describe "::NON_RAILS_QUERY_STRING_NORMALIZER" do let(:normalizer) { HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER } it "doesn't modify strings" do query_string = normalizer["foo=bar&foo=baz"] expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz") end context "when the query is an array" do it "doesn't include brackets" do query_string = normalizer[{page: 1, foo: %w(bar baz)}] expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1") end it "URI encodes array values" do query_string = normalizer[{people: ["Otis Redding", "Bob Marley", "Tim & Jon"], page: 1, xyzzy: 3}] expect(query_string).to eq("page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3") end end context "when the query is a hash" do it "correctly handles nil values" do query_string = normalizer[{page: 1, per_page: nil}] expect(query_string).to eq("page=1&per_page") end end end describe "::JSON_API_QUERY_STRING_NORMALIZER" do let(:normalizer) { HTTParty::Request::JSON_API_QUERY_STRING_NORMALIZER } it "doesn't modify strings" do query_string = normalizer["foo=bar&foo=baz"] expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz") end context "when the query is an array" do it "doesn't include brackets" do query_string = normalizer[{page: 1, foo: %w(bar baz)}] expect(CGI.unescape(query_string)).to eq("foo=bar,baz&page=1") end it "URI encodes array values" do query_string = normalizer[{people: ["Otis Redding", "Bob Marley", "Tim & Jon"], page: 1, xyzzy: 3}] expect(query_string).to eq("page=1&people=Otis%20Redding,Bob%20Marley,Tim%20%26%20Jon&xyzzy=3") end end context "when the query is a hash" do it "correctly handles nil values" do query_string = normalizer[{page: 1, per_page: nil}] expect(query_string).to eq('page=1&per_page') end end end describe "initialization" do it "sets parser to HTTParty::Parser" do request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com') expect(request.parser).to eq(HTTParty::Parser) end it "sets parser to the optional parser" do my_parser = lambda {} request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', parser: my_parser) expect(request.parser).to eq(my_parser) end it "sets connection_adapter to HTTParty::ConnectionAdapter" do request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com') expect(request.connection_adapter).to eq(HTTParty::ConnectionAdapter) end it "sets connection_adapter to the optional connection_adapter" do my_adapter = lambda {} request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', connection_adapter: my_adapter) expect(request.connection_adapter).to eq(my_adapter) end context "when using a query string" do context "and it has an empty array" do it "sets correct query string" do request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [] }) expect(request.uri).to eq(URI.parse("http://google.com/?fake_array%5B%5D=")) end end context "when sending an array with only one element" do it "sets correct query" do request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [1] }) expect(request.uri).to eq(URI.parse("http://google.com/?fake_array%5B%5D=1")) end end end context "when basic authentication credentials provided in uri" do context "when basic auth options wasn't set explicitly" do it "sets basic auth from uri" do request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com') expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'}) end end context "when basic auth options was set explicitly" do it "uses basic auth from url anyway" do basic_auth = {username: 'user2', password: 'pass2'} request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', basic_auth: basic_auth) expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'}) end end end end describe "#format" do context "request yet to be made" do it "returns format option" do request = HTTParty::Request.new 'get', '/', format: :xml expect(request.format).to eq(:xml) end it "returns nil format" do request = HTTParty::Request.new 'get', '/' expect(request.format).to be_nil end end context "request has been made" do it "returns format option" do request = HTTParty::Request.new 'get', '/', format: :xml request.last_response = double expect(request.format).to eq(:xml) end it "returns the content-type from the last response when the option is not set" do request = HTTParty::Request.new 'get', '/' response = double expect(response).to receive(:[]).with('content-type').and_return('text/json') request.last_response = response expect(request.format).to eq(:json) end end end context "options" do it "should use basic auth when configured" do @request.options[:basic_auth] = {username: 'foobar', password: 'secret'} @request.send(:setup_raw_request) expect(@request.instance_variable_get(:@raw_request)['authorization']).not_to be_nil end context 'digest_auth' do before do response_sequence = [ { status: ['401', 'Unauthorized' ], headers: { www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false', set_cookie: 'custom-cookie=1234567' } }, { status: ['200', 'OK'] } ] stub_request(:get, 'http://api.foo.com/v1').to_return(response_sequence) end it 'should not send credentials more than once' do response_sequence = [ { status: ['401', 'Unauthorized' ], headers: { www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false', set_cookie: 'custom-cookie=1234567' } }, { status: ['401', 'Unauthorized' ], headers: { www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false', set_cookie: 'custom-cookie=1234567' } }, { status: ['404', 'Not found'] } ] stub_request(:get, 'http://api.foo.com/v1').to_return(response_sequence) @request.options[:digest_auth] = {username: 'foobar', password: 'secret'} response = @request.perform { |v| } expect(response.code).to eq(401) raw_request = @request.instance_variable_get(:@raw_request) expect(raw_request['Authorization']).not_to be_nil end it 'should not be used when configured and the response is 200' do stub_request(:get, 'http://api.foo.com/v1').to_return(status: 200) @request.options[:digest_auth] = {username: 'foobar', password: 'secret'} response = @request.perform { |v| } expect(response.code).to eq(200) raw_request = @request.instance_variable_get(:@raw_request) expect(raw_request['Authorization']).to be_nil end it "should be used when configured and the response is 401" do @request.options[:digest_auth] = {username: 'foobar', password: 'secret'} response = @request.perform { |v| } expect(response.code).to eq(200) raw_request = @request.instance_variable_get(:@raw_request) expect(raw_request['Authorization']).not_to be_nil end it 'should maintain cookies returned from a 401 response' do @request.options[:digest_auth] = {username: 'foobar', password: 'secret'} response = @request.perform {|v|} expect(response.code).to eq(200) raw_request = @request.instance_variable_get(:@raw_request) expect(raw_request.get_fields('cookie')).to eql ["custom-cookie=1234567"] end it 'should merge cookies from request and a 401 response' do @request.options[:digest_auth] = {username: 'foobar', password: 'secret'} @request.options[:headers] = {'cookie' => 'request-cookie=test'} response = @request.perform {|v|} expect(response.code).to eq(200) raw_request = @request.instance_variable_get(:@raw_request) expect(raw_request.get_fields('cookie')).to eql ['request-cookie=test', 'custom-cookie=1234567'] end end it 'should use body_stream when configured' do stream = StringIO.new('foo') request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body_stream: stream) request.send(:setup_raw_request) expect(request.instance_variable_get(:@raw_request).body_stream).to eq(stream) end context 'with file upload' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } after { file.close } it 'should use body_stream for streaming multipart uploads by default' do request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body: { avatar: file }) request.send(:setup_raw_request) raw_request = request.instance_variable_get(:@raw_request) expect(raw_request.body_stream).to be_a(HTTParty::Request::StreamingMultipartBody) expect(raw_request.body).to be_nil expect(raw_request['Content-Length']).not_to be_nil end it 'should set correct Content-Length header from stream size' do request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body: { avatar: file }) request.send(:setup_raw_request) raw_request = request.instance_variable_get(:@raw_request) stream = raw_request.body_stream expect(raw_request['Content-Length'].to_i).to eq(stream.size) end it 'should fall back to non-streaming when stream_body is false' do request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body: { avatar: file }, stream_body: false) request.send(:setup_raw_request) raw_request = request.instance_variable_get(:@raw_request) expect(raw_request.body_stream).to be_nil expect(raw_request.body).not_to be_nil expect(raw_request.body).to be_a(String) end it 'streaming body produces same content as non-streaming' do allow(HTTParty::Request::MultipartBoundary).to receive(:generate).and_return('test-boundary-123') # Get streaming content request1 = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body: { avatar: file }) request1.send(:setup_raw_request) streaming_content = request1.instance_variable_get(:@raw_request).body_stream.read file.rewind # Get non-streaming content request2 = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body: { avatar: file }, stream_body: false) request2.send(:setup_raw_request) non_streaming_content = request2.instance_variable_get(:@raw_request).body expect(streaming_content).to eq(non_streaming_content) end end it 'should normalize base uri when specified as request option' do stub_request(:get, 'http://foo.com/resource').to_return(body: 'Bar') response = HTTParty.get('/resource', { base_uri: 'foo.com' }) expect(response.code).to eq(200) end end describe "#uri" do context "redirects" do it "returns correct path when the server sets the location header to a filename" do @request.last_uri = URI.parse("http://example.com/foo/bar") @request.path = URI.parse("bar?foo=bar") @request.redirect = true expect(@request.uri).to eq(URI.parse("http://example.com/foo/bar?foo=bar")) end context "location header is an absolute path" do it "returns correct path when location has leading slash" do @request.last_uri = URI.parse("http://example.com/foo/bar") @request.path = URI.parse("/bar?foo=bar") @request.redirect = true expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar")) end it "returns the correct path when location has no leading slash" do @request.last_uri = URI.parse("http://example.com") @request.path = URI.parse("bar/") @request.redirect = true expect(@request.uri).to eq(URI.parse("http://example.com/bar/")) end end it "returns correct path when the server sets the location header to a full uri" do @request.last_uri = URI.parse("http://example.com/foo/bar") @request.path = URI.parse("http://example.com/bar?foo=bar") @request.redirect = true expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar")) end it "returns correct path when the server sets the location header to a network-path reference" do @request.last_uri = URI.parse("https://example.com") @request.path = URI.parse("//www.example.com") @request.redirect = true expect(@request.uri).to eq(URI.parse("https://www.example.com")) end end context "query strings" do it "does not add an empty query string when default_params are blank" do @request.options[:default_params] = {} expect(@request.uri.query).to be_nil end it "respects the query string normalization proc" do empty_proc = lambda {|qs| "I"} @request.options[:query_string_normalizer] = empty_proc @request.options[:query] = {foo: :bar} expect(CGI.unescape(@request.uri.query)).to eq("I") end it "does not append an ampersand when queries are embedded in paths" do @request.path = "/path?a=1" @request.options[:query] = {} expect(@request.uri.query).to eq("a=1") end it "does not duplicate query string parameters when uri is called twice" do @request.options[:query] = {foo: :bar} @request.uri expect(@request.uri.query).to eq("foo=bar") end context "when representing an array" do it "returns a Rails style query string" do @request.options[:query] = {foo: %w(bar baz)} expect(CGI.unescape(@request.uri.query)).to eq("foo[]=bar&foo[]=baz") expect(@request.uri.query).to eq("foo%5B%5D=bar&foo%5B%5D=baz") end end end context "URI safety validation" do context "when base_uri is configured" do it "raises UnsafeURIError when path is an absolute URL with different host" do request = HTTParty::Request.new( Net::HTTP::Get, 'http://evil.com/steal-data', base_uri: 'http://trusted.com' ) expect { request.uri }.to raise_error( HTTParty::UnsafeURIError, /has host 'evil.com' but the configured base_uri .* has host 'trusted.com'/ ) end it "allows requests when path host matches base_uri host" do request = HTTParty::Request.new( Net::HTTP::Get, 'http://trusted.com/api/data', base_uri: 'http://trusted.com' ) expect { request.uri }.not_to raise_error expect(request.uri.host).to eq('trusted.com') end it "allows relative paths" do request = HTTParty::Request.new( Net::HTTP::Get, '/api/data', base_uri: 'http://trusted.com' ) expect { request.uri }.not_to raise_error expect(request.uri.to_s).to eq('http://trusted.com/api/data') end it "raises UnsafeURIError for network-relative URLs with different host" do @request.last_uri = URI.parse("https://trusted.com") @request.path = URI.parse("//evil.com/steal") @request.redirect = true @request.options[:base_uri] = 'http://trusted.com' # During redirects, URI safety is not checked to allow legitimate redirects expect { @request.uri }.not_to raise_error end it "can be bypassed with skip_uri_validation option" do request = HTTParty::Request.new( Net::HTTP::Get, 'http://other.com/api/data', base_uri: 'http://trusted.com', skip_uri_validation: true ) expect { request.uri }.not_to raise_error expect(request.uri.host).to eq('other.com') end end context "when base_uri is not configured" do it "allows absolute URLs" do request = HTTParty::Request.new( Net::HTTP::Get, 'http://any-server.com/api/data' ) expect { request.uri }.not_to raise_error expect(request.uri.host).to eq('any-server.com') end end end end describe "#setup_raw_request" do context "when query_string_normalizer is set" do it "sets the body to the return value of the proc" do @request.options[:query_string_normalizer] = HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER @request.options[:body] = {page: 1, foo: %w(bar baz)} @request.send(:setup_raw_request) body = @request.instance_variable_get(:@raw_request).body expect(CGI.unescape(body)).to eq("foo=bar&foo=baz&page=1") end end context "when multipart" do subject(:headers) do @request.send(:setup_raw_request) headers = @request.instance_variable_get(:@raw_request).each_header.to_a Hash[*headers.flatten] # Ruby 2.0 doesn't have Array#to_h end context "when body contains file" do it "sets header Content-Type: multipart/form-data; boundary=" do @request.options[:body] = {file: File.open(File::NULL, 'r')} expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---}) end context "and header Content-Type is provided" do it "overwrites the header to: multipart/form-data; boundary=" do @request.options[:body] = {file: File.open(File::NULL, 'r')} @request.options[:headers] = {'Content-Type' => 'application/x-www-form-urlencoded'} expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---}) end end end context 'when mulipart option is provided' do it "sets header Content-Type: multipart/form-data; boundary=" do @request.options[:body] = { text: 'something' } @request.options[:multipart] = true expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---}) end end end context "when body is a Hash" do subject(:headers) do @request.send(:setup_raw_request) headers = @request.instance_variable_get(:@raw_request).each_header.to_a Hash[*headers.flatten] end it "sets header Content-Type: application/x-www-form-urlencoded" do @request.options[:body] = { foo: 'bar' } expect(headers['content-type']).to eq('application/x-www-form-urlencoded') end context "and header Content-Type is provided" do it "does not overwrite the provided Content-Type" do @request.options[:body] = { foo: 'bar' } @request.options[:headers] = { 'Content-Type' => 'application/json' } expect(headers['content-type']).to eq('application/json') end end end end describe 'http' do it "should get a connection from the connection_adapter" do http = Net::HTTP.new('google.com') adapter = double('adapter') request = HTTParty::Request.new(Net::HTTP::Get, 'https://api.foo.com/v1:443', connection_adapter: adapter) expect(adapter).to receive(:call).with(request.uri, request.options).and_return(http) expect(request.send(:http)).to be http end end describe '#format_from_mimetype' do it 'should handle text/xml' do ["text/xml", "text/xml; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:xml) end end it 'should handle application/xml' do ["application/xml", "application/xml; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:xml) end end it 'should handle text/json' do ["text/json", "text/json; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:json) end end it 'should handle application/vnd.api+json' do ["application/vnd.api+json", "application/vnd.api+json; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:json) end end it 'should handle application/hal+json' do ["application/hal+json", "application/hal+json; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:json) end end it 'should handle application/json' do ["application/json", "application/json; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:json) end end it 'should handle text/csv' do ["text/csv", "text/csv; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:csv) end end it 'should handle application/csv' do ["application/csv", "application/csv; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:csv) end end it 'should handle text/comma-separated-values' do ["text/comma-separated-values", "text/comma-separated-values; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:csv) end end it 'should handle text/javascript' do ["text/javascript", "text/javascript; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:plain) end end it 'should handle application/javascript' do ["application/javascript", "application/javascript; charset=iso8859-1"].each do |ct| expect(@request.send(:format_from_mimetype, ct)).to eq(:plain) end end it "returns nil for an unrecognized mimetype" do expect(@request.send(:format_from_mimetype, "application/atom+xml")).to be_nil end it "returns nil when using a default parser" do @request.options[:parser] = lambda {} expect(@request.send(:format_from_mimetype, "text/json")).to be_nil end end describe 'parsing responses' do it 'should handle xml automatically' do xml = '<books><book><id>1234</id><name>Foo Bar!</name></book></books>' @request.options[:format] = :xml expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}) end it 'should handle utf-8 bom in xml' do xml = "\xEF\xBB\xBF<books><book><id>1234</id><name>Foo Bar!</name></book></books>" @request.options[:format] = :xml expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}) end it 'should handle csv automatically' do csv = ['"id","Name"', '"1234","Foo Bar!"'].join("\n") @request.options[:format] = :csv expect(@request.send(:parse_response, csv)).to eq([%w(id Name), ["1234", "Foo Bar!"]]) end it 'should handle json automatically' do json = '{"books": {"book": {"name": "Foo Bar!", "id": "1234"}}}' @request.options[:format] = :json expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}) end it 'should handle utf-8 bom in json' do json = "\xEF\xBB\xBF{\"books\": {\"book\": {\"name\": \"Foo Bar!\", \"id\": \"1234\"}}}" @request.options[:format] = :json expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}) end it "should include any HTTP headers in the returned response" do @request.options[:format] = :html response = stub_response "Content" response.initialize_http_header("key" => "value") expect(@request.perform.headers).to eq({ "key" => ["value"] }) end describe 'decompression' do it 'should remove the Content-Encoding header if uncompressed' do @request.options[:format] = :html response = stub_response 'Content' response.initialize_http_header('Content-Encoding' => 'none') resp = @request.perform expect(resp.body).to eq('Content') expect(resp.headers).to eq({}) expect(resp.parsed_response).to eq('Content') end it 'should decompress the body and remove the Content-Encoding header' do @request.options[:format] = :html stub_const('Brotli', double('Brotli', inflate: 'foobar')) response = stub_response 'Content' response.initialize_http_header('Content-Encoding' => 'br') resp = @request.perform expect(resp.body).to eq('foobar') expect(resp.headers).to eq({}) expect(resp.parsed_response).to eq('foobar') end it 'should not decompress the body if the :skip_decompression option is set' do @request.options[:format] = :html @request.options[:skip_decompression] = true stub_const('Brotli', double('Brotli', inflate: 'foobar')) response = stub_response 'Content' response.initialize_http_header('Content-Encoding' => 'br') resp = @request.perform expect(resp.body).to eq('Content') expect(resp.headers).to eq({ 'Content-Encoding' => 'br' }) expect(resp.parsed_response).to eq('foobar') end it 'should not decompress unrecognized Content-Encoding' do @request.options[:format] = :html response = stub_response 'Content' response.initialize_http_header('Content-Encoding' => 'bad') resp = @request.perform expect(resp.body).to eq('Content') expect(resp.headers).to eq({ 'Content-Encoding' => 'bad' }) expect(resp.parsed_response).to eq(nil) end end if "".respond_to?(:encoding) context 'when body has ascii-8bit encoding' do let(:response) { stub_response "Content".force_encoding('ascii-8bit') } it "processes charset in content type properly" do response.initialize_http_header("Content-Type" => "text/plain;charset = utf-8") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-8")) end it "processes charset in content type properly if it has a different case" do response.initialize_http_header("Content-Type" => "text/plain;CHARSET = utf-8") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-8")) end it "processes quoted charset in content type properly" do response.initialize_http_header("Content-Type" => "text/plain;charset = \"utf-8\"") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-8")) end context 'when stubed body is frozen' do let(:response) do stub_response "Content".force_encoding('ascii-8bit').freeze end it 'processes frozen body correctly' do response.initialize_http_header("Content-Type" => "text/plain;charset = utf-8") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-8")) end end end it "should process response with a nil body" do response = stub_response nil response.initialize_http_header("Content-Type" => "text/html;charset=UTF-8") resp = @request.perform expect(resp.body).to be_nil end context 'when assume_utf16_is_big_endian is true' do before { @request.options[:assume_utf16_is_big_endian] = true } it "should process utf-16 charset with little endian bom correctly" do response = stub_response "\xFF\xFEC\x00o\x00n\x00t\x00e\x00n\x00t\x00" response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE")) end it 'processes stubbed frozen body correctly' do response = stub_response "\xFF\xFEC\x00o\x00n\x00t\x00e\x00n\x00t\x00".freeze response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE")) end end it "should process utf-16 charset with big endian bom correctly" do @request.options[:assume_utf16_is_big_endian] = false response = stub_response "\xFE\xFF\x00C\x00o\x00n\x00t\x00e\x00n\x00t" response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-16BE")) end it "should assume utf-16 little endian if options has been chosen" do @request.options[:assume_utf16_is_big_endian] = false response = stub_response "C\x00o\x00n\x00t\x00e\x00n\x00t\x00" response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16") resp = @request.perform expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE")) end it "should perform no encoding if the charset is not available" do response = stub_response "Content" response.initialize_http_header("Content-Type" => "text/plain;charset = utf-lols") resp = @request.perform # This encoding does not exist, thus the string should not be encodd with it expect(resp.body).to eq("Content") expect(resp.body.encoding).to eq("Content".encoding) end it "should perform no encoding if the content type is specified but no charset is specified" do response = stub_response "Content" response.initialize_http_header("Content-Type" => "text/plain") resp = @request.perform expect(resp.body).to eq("Content") expect(resp.body.encoding).to eq("Content".encoding) end end describe 'with non-200 responses' do context "3xx responses" do it 'returns a valid object for 304 not modified' do stub_response '', 304 resp = @request.perform expect(resp.code).to eq(304) expect(resp.body).to eq('') expect(resp).to be_nil end it "redirects if a 300 contains a location header" do redirect = stub_response '', 300 redirect['location'] = 'http://foo.com/foo' ok = stub_response('<hash><foo>bar</foo></hash>', 200) allow(@http).to receive(:request).and_return(redirect, ok) response = @request.perform expect(response.request.base_uri.to_s).to eq("http://foo.com") expect(response.request.path.to_s).to eq("http://foo.com/foo") expect(response.request.uri.request_uri).to eq("/foo") expect(response.request.uri.to_s).to eq("http://foo.com/foo") expect(response.parsed_response).to eq({"hash" => {"foo" => "bar"}}) end it "calls block given to perform with each redirect" do @request = HTTParty::Request.new(Net::HTTP::Get, 'http://test.com/redirect', format: :xml) stub_request(:get, 'http://test.com/redirect') .to_return( status: [300, 'REDIRECT'], headers: { location: 'http://api.foo.com/v2' } )
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
true
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/hash_conversions_spec.rb
spec/httparty/hash_conversions_spec.rb
require 'spec_helper' RSpec.describe HTTParty::HashConversions do describe ".to_params" do it "creates a params string from a hash" do hash = { name: "bob", address: { street: '111 ruby ave.', city: 'ruby central', phones: ['111-111-1111', '222-222-2222'] } } expect(HTTParty::HashConversions.to_params(hash)).to eq("name=bob&address%5Bstreet%5D=111%20ruby%20ave.&address%5Bcity%5D=ruby%20central&address%5Bphones%5D%5B%5D=111-111-1111&address%5Bphones%5D%5B%5D=222-222-2222") end context "nested params" do it 'creates a params string from a hash' do hash = { marketing_event: { marketed_resources: [ {type:"product", id: 57474842640 } ] } } expect(HTTParty::HashConversions.to_params(hash)).to eq("marketing_event%5Bmarketed_resources%5D%5B%5D%5Btype%5D=product&marketing_event%5Bmarketed_resources%5D%5B%5D%5Bid%5D=57474842640") end end end describe ".normalize_param" do context "value is an array" do it "creates a params string" do expect( HTTParty::HashConversions.normalize_param(:people, ["Bob Jones", "Mike Smith"]) ).to eq("people%5B%5D=Bob%20Jones&people%5B%5D=Mike%20Smith&") end end context "value is an empty array" do it "creates a params string" do expect( HTTParty::HashConversions.normalize_param(:people, []) ).to eq("people%5B%5D=&") end end context "value is hash" do it "creates a params string" do expect( HTTParty::HashConversions.normalize_param(:person, { name: "Bob Jones" }) ).to eq("person%5Bname%5D=Bob%20Jones&") end end context "value is a string" do it "creates a params string" do expect( HTTParty::HashConversions.normalize_param(:name, "Bob Jones") ).to eq("name=Bob%20Jones&") end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/decompressor_spec.rb
spec/httparty/decompressor_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Decompressor do describe '.SupportedEncodings' do it 'returns a hash' do expect(HTTParty::Decompressor::SupportedEncodings).to be_instance_of(Hash) end end describe '#decompress' do let(:body) { 'body' } let(:encoding) { 'none' } let(:decompressor) { described_class.new(body, encoding) } subject { decompressor.decompress } shared_examples 'returns nil' do it { expect(subject).to be_nil } end shared_examples 'returns the body' do it { expect(subject).to eq 'body' } end context 'when body is nil' do let(:body) { nil } it_behaves_like 'returns nil' end context 'when body is blank' do let(:body) { ' ' } it { expect(subject).to eq ' ' } end context 'when encoding is nil' do let(:encoding) { nil } it_behaves_like 'returns the body' end context 'when encoding is blank' do let(:encoding) { ' ' } it_behaves_like 'returns the body' end context 'when encoding is "none"' do let(:encoding) { 'none' } it_behaves_like 'returns the body' end context 'when encoding is "identity"' do let(:encoding) { 'identity' } it_behaves_like 'returns the body' end context 'when encoding is unsupported' do let(:encoding) { 'invalid' } it_behaves_like 'returns nil' end context 'when encoding is "br"' do let(:encoding) { 'br' } context 'when brotli gem not included' do it_behaves_like 'returns nil' end context 'when brotli included' do before do dbl = double('Brotli') expect(dbl).to receive(:inflate).with('body').and_return('foobar') stub_const('Brotli', dbl) end it { expect(subject).to eq 'foobar' } end context 'when brotli raises error' do before do dbl = double('brotli') expect(dbl).to receive(:inflate).with('body') { raise RuntimeError.new('brotli error') } stub_const('Brotli', dbl) end it { expect(subject).to eq nil } end end context 'when encoding is "compress"' do let(:encoding) { 'compress' } context 'when LZW gem not included' do it_behaves_like 'returns nil' end context 'when ruby-lzws included' do before do dbl = double('lzws') expect(dbl).to receive(:decompress).with('body').and_return('foobar') stub_const('LZWS::String', dbl) end it { expect(subject).to eq 'foobar' } end context 'when ruby-lzws raises error' do before do dbl = double('lzws') expect(dbl).to receive(:decompress).with('body') { raise RuntimeError.new('brotli error') } stub_const('LZWS::String', dbl) end it { expect(subject).to eq nil } end context 'when compress-lzw included' do before do dbl2 = double('lzw2') dbl = double('lzw1', new: dbl2) expect(dbl2).to receive(:decompress).with('body').and_return('foobar') stub_const('LZW::Simple', dbl) end it { expect(subject).to eq 'foobar' } end context 'when compress-lzw raises error' do before do dbl2 = double('lzw2') dbl = double('lzw1', new: dbl2) expect(dbl2).to receive(:decompress).with('body') { raise RuntimeError.new('brotli error') } stub_const('LZW::Simple', dbl) end end end context 'when encoding is "zstd"' do let(:encoding) { 'zstd' } context 'when zstd-ruby gem not included' do it_behaves_like 'returns nil' end context 'when zstd-ruby included' do before do dbl = double('Zstd') expect(dbl).to receive(:decompress).with('body').and_return('foobar') stub_const('Zstd', dbl) end it { expect(subject).to eq 'foobar' } end context 'when zstd raises error' do before do dbl = double('Zstd') expect(dbl).to receive(:decompress).with('body') { raise RuntimeError.new('zstd error') } stub_const('Zstd', dbl) end it { expect(subject).to eq nil } end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/ssl_spec.rb
spec/httparty/ssl_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Request do context "SSL certificate verification" do before do WebMock.disable! end after do WebMock.enable! end it "should fail when no trusted CA list is specified, by default" do expect do ssl_verify_test(nil, nil, "selfsigned.crt") end.to raise_error OpenSSL::SSL::SSLError end it "should work when no trusted CA list is specified, when the verify option is set to false" do expect(ssl_verify_test(nil, nil, "selfsigned.crt", verify: false).parsed_response).to eq({'success' => true}) end it "should fail when no trusted CA list is specified, with a bogus hostname, by default" do expect do ssl_verify_test(nil, nil, "bogushost.crt") end.to raise_error OpenSSL::SSL::SSLError end it "should work when no trusted CA list is specified, even with a bogus hostname, when the verify option is set to true" do expect(ssl_verify_test(nil, nil, "bogushost.crt", verify: false).parsed_response).to eq({'success' => true}) end it "should work when using ssl_ca_file with a self-signed CA" do expect(ssl_verify_test(:ssl_ca_file, "selfsigned.crt", "selfsigned.crt").parsed_response).to eq({'success' => true}) end it "should work when using ssl_ca_file with a certificate authority" do expect(ssl_verify_test(:ssl_ca_file, "ca.crt", "server.crt").parsed_response).to eq({'success' => true}) end it "should work when using ssl_ca_path with a certificate authority" do http = Net::HTTP.new('www.google.com', 443) response = double(Net::HTTPResponse, :[] => '', body: '', to_hash: {}, delete: nil) allow(http).to receive(:request).and_return(response) expect(Net::HTTP).to receive(:new).with('www.google.com', 443).and_return(http) expect(http).to receive(:ca_path=).with('/foo/bar') HTTParty.get('https://www.google.com', ssl_ca_path: '/foo/bar') end it "should fail when using ssl_ca_file and the server uses an unrecognized certificate authority" do expect do ssl_verify_test(:ssl_ca_file, "ca.crt", "selfsigned.crt") end.to raise_error(OpenSSL::SSL::SSLError) end it "should fail when using ssl_ca_path and the server uses an unrecognized certificate authority" do expect do ssl_verify_test(:ssl_ca_path, ".", "selfsigned.crt") end.to raise_error(OpenSSL::SSL::SSLError) end it "should fail when using ssl_ca_file and the server uses a bogus hostname" do expect do ssl_verify_test(:ssl_ca_file, "ca.crt", "bogushost.crt") end.to raise_error(OpenSSL::SSL::SSLError) end it "should fail when using ssl_ca_path and the server uses a bogus hostname" do expect do ssl_verify_test(:ssl_ca_path, ".", "bogushost.crt") end.to raise_error(OpenSSL::SSL::SSLError) end it "should provide the certificate used by the server via peer_cert" do peer_cert = nil ssl_verify_test(:ssl_ca_file, "ca.crt", "server.crt") do |response| peer_cert ||= response.connection.peer_cert end expect(peer_cert).to be_a OpenSSL::X509::Certificate end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/parser_spec.rb
spec/httparty/parser_spec.rb
require 'spec_helper' require 'multi_xml' RSpec.describe HTTParty::Parser do describe ".SupportedFormats" do it "returns a hash" do expect(HTTParty::Parser::SupportedFormats).to be_instance_of(Hash) end end describe ".call" do it "generates an HTTParty::Parser instance with the given body and format" do expect(HTTParty::Parser).to receive(:new).with('body', :plain).and_return(double(parse: nil)) HTTParty::Parser.call('body', :plain) end it "calls #parse on the parser" do parser = double('Parser') expect(parser).to receive(:parse) allow(HTTParty::Parser).to receive_messages(new: parser) parser = HTTParty::Parser.call('body', :plain) end end describe ".formats" do it "returns the SupportedFormats constant" do expect(HTTParty::Parser.formats).to eq(HTTParty::Parser::SupportedFormats) end it "returns the SupportedFormats constant for subclasses" do klass = Class.new(HTTParty::Parser) klass::SupportedFormats = { "application/atom+xml" => :atom } expect(klass.formats).to eq({"application/atom+xml" => :atom}) end end describe ".format_from_mimetype" do it "returns a symbol representing the format mimetype" do expect(HTTParty::Parser.format_from_mimetype("text/plain")).to eq(:plain) end it "returns nil when the mimetype is not supported" do expect(HTTParty::Parser.format_from_mimetype("application/atom+xml")).to be_nil end end describe ".supported_formats" do it "returns a unique set of supported formats represented by symbols" do expect(HTTParty::Parser.supported_formats).to eq(HTTParty::Parser::SupportedFormats.values.uniq) end end describe ".supports_format?" do it "returns true for a supported format" do allow(HTTParty::Parser).to receive_messages(supported_formats: [:json]) expect(HTTParty::Parser.supports_format?(:json)).to be_truthy end it "returns false for an unsupported format" do allow(HTTParty::Parser).to receive_messages(supported_formats: []) expect(HTTParty::Parser.supports_format?(:json)).to be_falsey end end describe "#parse" do it "attempts to parse supported formats" do parser = HTTParty::Parser.new('body', :json) allow(parser).to receive_messages(supports_format?: true) expect(parser).to receive(:parse_supported_format) parser.parse end it "returns the unparsed body when the format is unsupported" do parser = HTTParty::Parser.new('body', :json) allow(parser).to receive_messages(supports_format?: false) expect(parser.parse).to eq(parser.body) end it "returns nil for an empty body" do parser = HTTParty::Parser.new('', :json) expect(parser.parse).to be_nil end it "returns nil for a nil body" do parser = HTTParty::Parser.new(nil, :json) expect(parser.parse).to be_nil end it "returns nil for a 'null' body" do parser = HTTParty::Parser.new("null", :json) expect(parser.parse).to be_nil end it "returns nil for a body with spaces only" do parser = HTTParty::Parser.new(" ", :json) expect(parser.parse).to be_nil end it "does not raise exceptions for bodies with invalid encodings" do parser = HTTParty::Parser.new("\x80", :invalid_format) expect(parser.parse).to_not be_nil end it "ignores utf-8 bom" do parser = HTTParty::Parser.new("\xEF\xBB\xBF\{\"hi\":\"yo\"\}", :json) expect(parser.parse).to eq({"hi"=>"yo"}) end it "parses ascii 8bit encoding" do parser = HTTParty::Parser.new( "{\"currency\":\"\xE2\x82\xAC\"}".force_encoding('ASCII-8BIT'), :json ) expect(parser.parse).to eq({"currency" => "€"}) end it "parses frozen strings" do parser = HTTParty::Parser.new('{"a":1}'.freeze, :json) expect(parser.parse).to eq("a" => 1) end end describe "#supports_format?" do it "utilizes the class method to determine if the format is supported" do expect(HTTParty::Parser).to receive(:supports_format?).with(:json) parser = HTTParty::Parser.new('body', :json) parser.send(:supports_format?) end end describe "#parse_supported_format" do it "calls the parser for the given format" do parser = HTTParty::Parser.new('body', :json) expect(parser).to receive(:json) parser.send(:parse_supported_format) end context "when a parsing method does not exist for the given format" do it "raises an exception" do parser = HTTParty::Parser.new('body', :atom) expect do parser.send(:parse_supported_format) end.to raise_error(NotImplementedError, "HTTParty::Parser has not implemented a parsing method for the :atom format.") end it "raises a useful exception message for subclasses" do atom_parser = Class.new(HTTParty::Parser) do def self.name 'AtomParser' end end parser = atom_parser.new 'body', :atom expect do parser.send(:parse_supported_format) end.to raise_error(NotImplementedError, "AtomParser has not implemented a parsing method for the :atom format.") end end end context "parsers" do subject do HTTParty::Parser.new('body', nil) end it "parses xml with MultiXml" do expect(MultiXml).to receive(:parse).with('body') subject.send(:xml) end it "parses json with JSON" do expect(JSON).to receive(:parse).with('body', :quirks_mode => true, :allow_nan => true) subject.send(:json) end it "parses html by simply returning the body" do expect(subject.send(:html)).to eq('body') end it "parses plain text by simply returning the body" do expect(subject.send(:plain)).to eq('body') end it "parses csv with CSV" do require 'csv' expect(CSV).to receive(:parse).with('body') subject.send(:csv) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/cookie_hash_spec.rb
spec/httparty/cookie_hash_spec.rb
require 'spec_helper' RSpec.describe HTTParty::CookieHash do before(:each) do @cookie_hash = HTTParty::CookieHash.new end describe "#add_cookies" do describe "with a hash" do it "should add new key/value pairs to the hash" do @cookie_hash.add_cookies(foo: "bar") @cookie_hash.add_cookies(rofl: "copter") expect(@cookie_hash.length).to eql(2) end it "should overwrite any existing key" do @cookie_hash.add_cookies(foo: "bar") @cookie_hash.add_cookies(foo: "copter") expect(@cookie_hash.length).to eql(1) expect(@cookie_hash[:foo]).to eql("copter") end end describe "with a string" do it "should add new key/value pairs to the hash" do @cookie_hash.add_cookies("first=one; second=two; third") expect(@cookie_hash[:first]).to eq('one') expect(@cookie_hash[:second]).to eq('two') expect(@cookie_hash[:third]).to eq(nil) end it "should overwrite any existing key" do @cookie_hash[:foo] = 'bar' @cookie_hash.add_cookies("foo=tar") expect(@cookie_hash.length).to eql(1) expect(@cookie_hash[:foo]).to eql("tar") end it "should handle '=' within cookie value" do @cookie_hash.add_cookies("first=one=1; second=two=2==") expect(@cookie_hash.keys).to include(:first, :second) expect(@cookie_hash[:first]).to eq('one=1') expect(@cookie_hash[:second]).to eq('two=2==') end it "should handle an empty cookie parameter" do @cookie_hash.add_cookies("first=one; domain=mydomain.com; path=/; ; SameSite; Secure") expect(@cookie_hash.keys).to include(:first, :domain, :path, :SameSite, :Secure) end end describe 'with other class' do it "should error" do expect { @cookie_hash.add_cookies([]) }.to raise_error(RuntimeError) end end end # The regexen are required because Hashes aren't ordered, so a test against # a hardcoded string was randomly failing. describe "#to_cookie_string" do before(:each) do @cookie_hash.add_cookies(foo: "bar") @cookie_hash.add_cookies(rofl: "copter") @s = @cookie_hash.to_cookie_string end it "should format the key/value pairs, delimited by semi-colons" do expect(@s).to match(/foo=bar/) expect(@s).to match(/rofl=copter/) expect(@s).to match(/^\w+=\w+; \w+=\w+$/) end it "should not include client side only cookies" do @cookie_hash.add_cookies(path: "/") @s = @cookie_hash.to_cookie_string expect(@s).not_to match(/path=\//) end it "should not include SameSite attribute" do @cookie_hash.add_cookies(samesite: "Strict") @s = @cookie_hash.to_cookie_string expect(@s).not_to match(/samesite=Strict/) end it "should not include client side only cookies even when attributes use camal case" do @cookie_hash.add_cookies(Path: "/") @s = @cookie_hash.to_cookie_string expect(@s).not_to match(/Path=\//) end it "should not mutate the hash" do original_hash = { "session" => "91e25e8b-6e32-418d-c72f-2d18adf041cd", "Max-Age" => "15552000", "cart" => "91e25e8b-6e32-418d-c72f-2d18adf041cd", "httponly" => nil, "Path" => "/", "secure" => nil, } cookie_hash = HTTParty::CookieHash[original_hash] cookie_hash.to_cookie_string expect(cookie_hash).to eq(original_hash) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/net_digest_auth_spec.rb
spec/httparty/net_digest_auth_spec.rb
require 'spec_helper' RSpec.describe Net::HTTPHeader::DigestAuthenticator do def setup_digest(response) digest = Net::HTTPHeader::DigestAuthenticator.new("Mufasa", "Circle Of Life", "GET", "/dir/index.html", response) allow(digest).to receive(:random).and_return("deadbeef") allow(Digest::MD5).to receive(:hexdigest) { |str| "md5(#{str})" } digest end def authorization_header @digest.authorization_header.join(", ") end def cookie_header @digest.cookie_header end context 'Net::HTTPHeader#digest_auth' do let(:headers) { (Class.new do include Net::HTTPHeader def initialize @header = {} @path = '/' @method = 'GET' end end).new } let(:response){ (Class.new do include Net::HTTPHeader def initialize @header = {} self['WWW-Authenticate'] = 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"' end end).new } it 'should set the authorization header' do expect(headers['authorization']).to be_nil headers.digest_auth('user','pass', response) expect(headers['authorization']).to_not be_empty end end context "with a cookie value in the response header" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com"', 'Set-Cookie' => 'custom-cookie=1234567' }) end it "should set cookie header" do expect(cookie_header).to include('custom-cookie=1234567') end end context "without a cookie value in the response header" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com"' }) end it "should set empty cookie header array" do expect(cookie_header).to eql [] end end context "with an opaque value in the response header" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", opaque="solid"' }) end it "should set opaque" do expect(authorization_header).to include('opaque="solid"') end end context "without an opaque valid in the response header" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com"' }) end it "should not set opaque" do expect(authorization_header).not_to include("opaque=") end end context "with specified quality of protection (qop)" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"' }) end it "should set prefix" do expect(authorization_header).to match(/^Digest /) end it "should set username" do expect(authorization_header).to include('username="Mufasa"') end it "should set digest-uri" do expect(authorization_header).to include('uri="/dir/index.html"') end it "should set qop" do expect(authorization_header).to include('qop="auth"') end it "should set cnonce" do expect(authorization_header).to include('cnonce="md5(deadbeef)"') end it "should set nonce-count" do expect(authorization_header).to include("nc=00000001") end it "should set response" do request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))" expect(authorization_header).to include(%(response="#{request_digest}")) end end context "when quality of protection (qop) is unquoted" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop=auth' }) end it "should still set qop" do expect(authorization_header).to include('qop="auth"') end end context "with unspecified quality of protection (qop)" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE"' }) end it "should set prefix" do expect(authorization_header).to match(/^Digest /) end it "should set username" do expect(authorization_header).to include('username="Mufasa"') end it "should set digest-uri" do expect(authorization_header).to include('uri="/dir/index.html"') end it "should not set qop" do expect(authorization_header).not_to include("qop=") end it "should not set cnonce" do expect(authorization_header).not_to include("cnonce=") end it "should not set nonce-count" do expect(authorization_header).not_to include("nc=") end it "should set response" do request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:md5(GET:/dir/index.html))" expect(authorization_header).to include(%(response="#{request_digest}")) end end context "with http basic auth response when net digest auth expected" do it "should not fail" do @digest = setup_digest({ 'www-authenticate' => 'WWW-Authenticate: Basic realm="testrealm.com""' }) expect(authorization_header).to include("Digest") end end context "with multiple authenticate headers" do before do @digest = setup_digest({ 'www-authenticate' => 'NTLM, Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"' }) end it "should set prefix" do expect(authorization_header).to match(/^Digest /) end it "should set username" do expect(authorization_header).to include('username="Mufasa"') end it "should set digest-uri" do expect(authorization_header).to include('uri="/dir/index.html"') end it "should set qop" do expect(authorization_header).to include('qop="auth"') end it "should set cnonce" do expect(authorization_header).to include('cnonce="md5(deadbeef)"') end it "should set nonce-count" do expect(authorization_header).to include("nc=00000001") end it "should set response" do request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))" expect(authorization_header).to include(%(response="#{request_digest}")) end end context "with algorithm specified" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth", algorithm=MD5' }) end it "should recognise algorithm was specified" do expect( @digest.send :algorithm_present? ).to be(true) end it "should set the algorithm header" do expect(authorization_header).to include('algorithm="MD5"') end end context "with md5-sess algorithm specified" do before do @digest = setup_digest({ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth", algorithm=MD5-sess' }) end it "should recognise algorithm was specified" do expect( @digest.send :algorithm_present? ).to be(true) end it "should set the algorithm header" do expect(authorization_header).to include('algorithm="MD5-sess"') end it "should set response using md5-sess algorithm" do request_digest = "md5(md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:md5(deadbeef)):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))" expect(authorization_header).to include(%(response="#{request_digest}")) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/response_fragment_spec.rb
spec/httparty/response_fragment_spec.rb
require File.expand_path(File.join(File.dirname(__FILE__), '../spec_helper')) RSpec.describe HTTParty::ResponseFragment do it "access to fragment" do fragment = HTTParty::ResponseFragment.new("chunk", nil, nil) expect(fragment).to eq("chunk") end it "has access to delegators" do response = double(code: '200') connection = double fragment = HTTParty::ResponseFragment.new("chunk", response, connection) expect(fragment.code).to eq(200) expect(fragment.http_response).to eq response expect(fragment.connection).to eq connection end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/connection_adapter_spec.rb
spec/httparty/connection_adapter_spec.rb
require 'spec_helper' RSpec.describe HTTParty::ConnectionAdapter do describe "initialization" do let(:uri) { URI 'http://www.google.com' } it "takes a URI as input" do HTTParty::ConnectionAdapter.new(uri) end it "raises an ArgumentError if the uri is nil" do expect { HTTParty::ConnectionAdapter.new(nil) }.to raise_error ArgumentError end it "raises an ArgumentError if the uri is a String" do expect { HTTParty::ConnectionAdapter.new('http://www.google.com') }.to raise_error ArgumentError end it "sets the uri" do adapter = HTTParty::ConnectionAdapter.new(uri) expect(adapter.uri).to be uri end it "also accepts an optional options hash" do HTTParty::ConnectionAdapter.new(uri, {}) end it "sets the options" do options = {foo: :bar} adapter = HTTParty::ConnectionAdapter.new(uri, options) expect(adapter.options.keys).to include(:verify, :verify_peer, :foo) end end describe ".call" do let(:uri) { URI 'http://www.google.com' } let(:options) { { foo: :bar } } it "generates an HTTParty::ConnectionAdapter instance with the given uri and options" do expect(HTTParty::ConnectionAdapter).to receive(:new).with(uri, options).and_return(double(connection: nil)) HTTParty::ConnectionAdapter.call(uri, options) end it "calls #connection on the connection adapter" do adapter = double('Adapter') connection = double('Connection') expect(adapter).to receive(:connection).and_return(connection) allow(HTTParty::ConnectionAdapter).to receive_messages(new: adapter) expect(HTTParty::ConnectionAdapter.call(uri, options)).to be connection end end describe '#connection' do let(:uri) { URI 'http://www.google.com' } let(:options) { Hash.new } let(:adapter) { HTTParty::ConnectionAdapter.new(uri, options) } describe "the resulting connection" do subject { adapter.connection } it { is_expected.to be_an_instance_of Net::HTTP } context "using port 80" do let(:uri) { URI 'http://foobar.com' } it { is_expected.not_to use_ssl } end context "when dealing with ssl" do let(:uri) { URI 'https://foobar.com' } context "uses the system cert_store, by default" do let!(:system_cert_store) do system_cert_store = double('default_cert_store') expect(system_cert_store).to receive(:set_default_paths) expect(OpenSSL::X509::Store).to receive(:new).and_return(system_cert_store) system_cert_store end it { is_expected.to use_cert_store(system_cert_store) } end context "should use the specified cert store, when one is given" do let(:custom_cert_store) { double('custom_cert_store') } let(:options) { {cert_store: custom_cert_store} } it { is_expected.to use_cert_store(custom_cert_store) } end context "using port 443 for ssl" do let(:uri) { URI 'https://api.foo.com/v1:443' } it { is_expected.to use_ssl } end context "https scheme with default port" do it { is_expected.to use_ssl } end context "https scheme with non-standard port" do let(:uri) { URI 'https://foobar.com:123456' } it { is_expected.to use_ssl } end context "when ssl version is set" do let(:options) { {ssl_version: :TLSv1} } it "sets ssl version" do expect(subject.ssl_version).to eq(:TLSv1) end end end context "when dealing with IPv6" do let(:uri) { URI 'http://[fd00::1]' } it "strips brackets from the address" do expect(subject.address).to eq('fd00::1') end end context "specifying ciphers" do let(:options) { {ciphers: 'RC4-SHA' } } it "should set the ciphers on the connection" do expect(subject.ciphers).to eq('RC4-SHA') end end context "when timeout is not set" do it "doesn't set the timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false ) expect(http).not_to receive(:open_timeout=) expect(http).not_to receive(:read_timeout=) expect(http).not_to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when setting timeout" do context "to 5 seconds" do let(:options) { {timeout: 5} } describe '#open_timeout' do subject { super().open_timeout } it { is_expected.to eq(5) } end describe '#read_timeout' do subject { super().read_timeout } it { is_expected.to eq(5) } end describe '#write_timeout' do subject { super().write_timeout } it { is_expected.to eq(5) } end end context "and timeout is a string" do let(:options) { {timeout: "five seconds"} } it "doesn't set the timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false ) expect(http).not_to receive(:open_timeout=) expect(http).not_to receive(:read_timeout=) expect(http).not_to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end end context "when timeout is not set and read_timeout is set to 6 seconds" do let(:options) { {read_timeout: 6} } describe '#read_timeout' do subject { super().read_timeout } it { is_expected.to eq(6) } end it "should not set the open_timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0 ) expect(http).not_to receive(:open_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end it "should not set the write_timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0 ) expect(http).not_to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when timeout is set and read_timeout is set to 6 seconds" do let(:options) { {timeout: 5, read_timeout: 6} } describe '#open_timeout' do subject { super().open_timeout } it { is_expected.to eq(5) } end describe '#write_timeout' do subject { super().write_timeout } it { is_expected.to eq(5) } end describe '#read_timeout' do subject { super().read_timeout } it { is_expected.to eq(6) } end it "should override the timeout option" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0, :open_timeout= => 0, :write_timeout= => 0, ) expect(http).to receive(:open_timeout=) expect(http).to receive(:read_timeout=).twice expect(http).to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when timeout is not set and open_timeout is set to 7 seconds" do let(:options) { {open_timeout: 7} } describe '#open_timeout' do subject { super().open_timeout } it { is_expected.to eq(7) } end it "should not set the read_timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :open_timeout= => 0 ) expect(http).not_to receive(:read_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end it "should not set the write_timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :open_timeout= => 0 ) expect(http).not_to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when timeout is set and open_timeout is set to 7 seconds" do let(:options) { {timeout: 5, open_timeout: 7} } describe '#open_timeout' do subject { super().open_timeout } it { is_expected.to eq(7) } end describe '#write_timeout' do subject { super().write_timeout } it { is_expected.to eq(5) } end describe '#read_timeout' do subject { super().read_timeout } it { is_expected.to eq(5) } end it "should override the timeout option" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0, :open_timeout= => 0, :write_timeout= => 0, ) expect(http).to receive(:open_timeout=).twice expect(http).to receive(:read_timeout=) expect(http).to receive(:write_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when timeout is not set and write_timeout is set to 8 seconds" do let(:options) { {write_timeout: 8} } describe '#write_timeout' do subject { super().write_timeout } it { is_expected.to eq(8) } end it "should not set the open timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0, :open_timeout= => 0, :write_timeout= => 0, ) expect(http).not_to receive(:open_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end it "should not set the read timeout" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0, :open_timeout= => 0, :write_timeout= => 0, ) expect(http).not_to receive(:read_timeout=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end context "when timeout is set and write_timeout is set to 8 seconds" do let(:options) { {timeout: 2, write_timeout: 8} } describe '#write_timeout' do subject { super().write_timeout } it { is_expected.to eq(8) } end it "should override the timeout option" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false, :read_timeout= => 0, :open_timeout= => 0, :write_timeout= => 0, ) expect(http).to receive(:read_timeout=) expect(http).to receive(:open_timeout=) expect(http).to receive(:write_timeout=).twice allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end end context "when max_retries is not set" do it "doesn't set the max_retries" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false ) expect(http).not_to receive(:max_retries=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end context "when setting max_retries" do context "to 5 times" do let(:options) { {max_retries: 5} } describe '#max_retries' do subject { super().max_retries } it { is_expected.to eq(5) } end end context "to 0 times" do let(:options) { {max_retries: 0} } describe '#max_retries' do subject { super().max_retries } it { is_expected.to eq(0) } end end context "and max_retries is a string" do let(:options) { {max_retries: "five times"} } it "doesn't set the max_retries" do http = double( "http", :null_object => true, :use_ssl= => false, :use_ssl? => false ) expect(http).not_to receive(:max_retries=) allow(Net::HTTP).to receive_messages(new: http) adapter.connection end end end context "when debug_output" do let(:http) { Net::HTTP.new(uri) } before do allow(Net::HTTP).to receive_messages(new: http) end context "is set to $stderr" do let(:options) { {debug_output: $stderr} } it "has debug output set" do expect(http).to receive(:set_debug_output).with($stderr) adapter.connection end end context "is not provided" do it "does not set_debug_output" do expect(http).not_to receive(:set_debug_output) adapter.connection end end end context 'when providing proxy address and port' do let(:options) { {http_proxyaddr: '1.2.3.4', http_proxyport: 8080} } it { is_expected.to be_a_proxy } describe '#proxy_address' do subject { super().proxy_address } it { is_expected.to eq('1.2.3.4') } end describe '#proxy_port' do subject { super().proxy_port } it { is_expected.to eq(8080) } end context 'as well as proxy user and password' do let(:options) do { http_proxyaddr: '1.2.3.4', http_proxyport: 8080, http_proxyuser: 'user', http_proxypass: 'pass' } end describe '#proxy_user' do subject { super().proxy_user } it { is_expected.to eq('user') } end describe '#proxy_pass' do subject { super().proxy_pass } it { is_expected.to eq('pass') } end end end context 'when providing nil as proxy address' do let(:uri) { URI 'http://noproxytest.com' } let(:options) { {http_proxyaddr: nil} } it { is_expected.not_to be_a_proxy } it "does pass nil proxy parameters to the connection, this forces to not use a proxy" do http = Net::HTTP.new("noproxytest.com") expect(Net::HTTP).to receive(:new).once.with("noproxytest.com", 80, nil, nil, nil, nil).and_return(http) adapter.connection end end context 'when not providing a proxy address' do let(:uri) { URI 'http://proxytest.com' } it "does not pass any proxy parameters to the connection" do http = Net::HTTP.new("proxytest.com") expect(Net::HTTP).to receive(:new).once.with("proxytest.com", 80).and_return(http) adapter.connection end end context 'when providing a local bind address and port' do let(:options) { {local_host: "127.0.0.1", local_port: 12345 } } describe '#local_host' do subject { super().local_host } it { is_expected.to eq('127.0.0.1') } end describe '#local_port' do subject { super().local_port } it { is_expected.to eq(12345) } end end context "when providing PEM certificates" do let(:pem) { :pem_contents } let(:options) { {pem: pem, pem_password: "password"} } context "when scheme is https" do let(:uri) { URI 'https://google.com' } let(:cert) { double("OpenSSL::X509::Certificate") } let(:key) { double("OpenSSL::PKey::RSA") } before do expect(OpenSSL::X509::Certificate).to receive(:new).with(pem).and_return(cert) expect(OpenSSL::PKey).to receive(:read).with(pem, "password").and_return(key) end it "uses the provided PEM certificate" do expect(subject.cert).to eq(cert) expect(subject.key).to eq(key) end it "will verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end context "when options include verify=false" do let(:options) { {pem: pem, pem_password: "password", verify: false} } it "should not verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end end context "when options include verify_peer=false" do let(:options) { {pem: pem, pem_password: "password", verify_peer: false} } it "should not verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end end end context "when scheme is not https" do let(:uri) { URI 'http://google.com' } let(:http) { Net::HTTP.new(uri) } before do allow(Net::HTTP).to receive_messages(new: http) expect(OpenSSL::X509::Certificate).not_to receive(:new).with(pem) expect(OpenSSL::PKey::RSA).not_to receive(:new).with(pem, "password") expect(http).not_to receive(:cert=) expect(http).not_to receive(:key=) end it "has no PEM certificate " do expect(subject.cert).to be_nil expect(subject.key).to be_nil end end end context "when providing PKCS12 certificates" do let(:p12) { :p12_contents } let(:options) { {p12: p12, p12_password: "password"} } context "when scheme is https" do let(:uri) { URI 'https://google.com' } let(:pkcs12) { double("OpenSSL::PKCS12", certificate: cert, key: key) } let(:cert) { double("OpenSSL::X509::Certificate") } let(:key) { double("OpenSSL::PKey::RSA") } before do expect(OpenSSL::PKCS12).to receive(:new).with(p12, "password").and_return(pkcs12) end it "uses the provided P12 certificate " do expect(subject.cert).to eq(cert) expect(subject.key).to eq(key) end it "will verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end context "when options include verify=false" do let(:options) { {p12: p12, p12_password: "password", verify: false} } it "should not verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end end context "when options include verify_peer=false" do let(:options) { {p12: p12, p12_password: "password", verify_peer: false} } it "should not verify the certificate" do expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end end end context "when scheme is not https" do let(:uri) { URI 'http://google.com' } let(:http) { Net::HTTP.new(uri) } before do allow(Net::HTTP).to receive_messages(new: http) expect(OpenSSL::PKCS12).not_to receive(:new).with(p12, "password") expect(http).not_to receive(:cert=) expect(http).not_to receive(:key=) end it "has no PKCS12 certificate " do expect(subject.cert).to be_nil expect(subject.key).to be_nil end end end context "when uri port is not defined" do context "falls back to 80 port on http" do let(:uri) { URI 'http://foobar.com' } before { allow(uri).to receive(:port).and_return(nil) } it { expect(subject.port).to be 80 } end context "falls back to 443 port on https" do let(:uri) { URI 'https://foobar.com' } before { allow(uri).to receive(:port).and_return(nil) } it { expect(subject.port).to be 443 } end end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/logger/curl_formatter_spec.rb
spec/httparty/logger/curl_formatter_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Logger::CurlFormatter do describe "#format" do let(:logger) { double('Logger') } let(:response_object) { Net::HTTPOK.new('1.1', 200, 'OK') } let(:parsed_response) { lambda { {"foo" => "bar"} } } let(:response) do HTTParty::Response.new(request, response_object, parsed_response) end let(:request) do HTTParty::Request.new(Net::HTTP::Get, 'http://foo.bar.com/') end subject { described_class.new(logger, :info) } before do allow(logger).to receive(:info) allow(request).to receive(:raw_body).and_return('content') allow(response_object).to receive_messages(body: "{foo:'bar'}") response_object['header-key'] = 'header-value' subject.format request, response end context 'when request is logged' do context "and request's option 'base_uri' is not present" do it 'logs url' do expect(logger).to have_received(:info).with(/\[HTTParty\] \[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\ [+-]\d{4}\] > GET http:\/\/foo.bar.com/) end end context "and request's option 'base_uri' is present" do let(:request) do HTTParty::Request.new(Net::HTTP::Get, '/path', base_uri: 'http://foo.bar.com') end it 'logs url' do expect(logger).to have_received(:info).with(/\[HTTParty\] \[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\ [+-]\d{4}\] > GET http:\/\/foo.bar.com\/path/) end end context 'and headers are not present' do it 'not log Headers' do expect(logger).not_to have_received(:info).with(/Headers/) end end context 'and headers are present' do let(:request) do HTTParty::Request.new(Net::HTTP::Get, '/path', base_uri: 'http://foo.bar.com', headers: { key: 'value' }) end it 'logs Headers' do expect(logger).to have_received(:info).with(/Headers/) end it 'logs headers keys' do expect(logger).to have_received(:info).with(/key: value/) end end context 'and query is not present' do it 'not logs Query' do expect(logger).not_to have_received(:info).with(/Query/) end end context 'and query is present' do let(:request) do HTTParty::Request.new(Net::HTTP::Get, '/path', query: { key: 'value' }) end it 'logs Query' do expect(logger).to have_received(:info).with(/Query/) end it 'logs query params' do expect(logger).to have_received(:info).with(/key: value/) end end context 'when request raw_body is present' do it 'not logs request body' do expect(logger).to have_received(:info).with(/content/) end end end context 'when response is logged' do it 'logs http version and response code' do expect(logger).to have_received(:info).with(/HTTP\/1.1 200/) end it 'logs headers' do expect(logger).to have_received(:info).with(/Header-key: header-value/) end it 'logs body' do expect(logger).to have_received(:info).with(/{foo:'bar'}/) end end it "formats a response in a style that resembles a -v curl" do logger_double = double expect(logger_double).to receive(:info).with( /\[HTTParty\] \[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\ [+-]\d{4}\] > GET http:\/\/localhost/) subject = described_class.new(logger_double, :info) stub_http_response_with("example.html") response = HTTParty::Request.new.perform subject.format(response.request, response) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/logger/apache_formatter_spec.rb
spec/httparty/logger/apache_formatter_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Logger::ApacheFormatter do let(:subject) { described_class.new(logger_double, :info) } let(:logger_double) { double('Logger') } let(:request_double) { double('Request', http_method: Net::HTTP::Get, path: "http://my.domain.com/my_path") } let(:request_time) { Time.new.strftime("%Y-%m-%d %H:%M:%S %z") } before do expect(logger_double).to receive(:info).with(log_message) end describe "#format" do let(:log_message) { "[HTTParty] [#{request_time}] 302 \"GET http://my.domain.com/my_path\" - " } it "formats a response in a style that resembles apache's access log" do response_double = double( code: 302, :[] => nil ) subject.format(request_double, response_double) end context 'when there is a parsed response' do let(:log_message) { "[HTTParty] [#{request_time}] 200 \"GET http://my.domain.com/my_path\" 512 "} it "can handle the Content-Length header" do # Simulate a parsed response that is an array, where accessing a string key will raise an error. See Issue #299. response_double = double( code: 200, headers: { 'Content-Length' => 512 } ) allow(response_double).to receive(:[]).with('Content-Length').and_raise(TypeError.new('no implicit conversion of String into Integer')) subject.format(request_double, response_double) end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/logger/logger_spec.rb
spec/httparty/logger/logger_spec.rb
require 'spec_helper' RSpec.describe HTTParty::Logger do describe ".build" do subject { HTTParty::Logger } it "defaults level to :info" do logger_double = double expect(subject.build(logger_double, nil, nil).level).to eq(:info) end it "defaults format to :apache" do logger_double = double expect(subject.build(logger_double, nil, nil)).to be_an_instance_of(HTTParty::Logger::ApacheFormatter) end it "builds :curl style logger" do logger_double = double expect(subject.build(logger_double, nil, :curl)).to be_an_instance_of(HTTParty::Logger::CurlFormatter) end it "builds :logstash style logger" do logger_double = double expect(subject.build(logger_double, nil, :logstash)).to be_an_instance_of(HTTParty::Logger::LogstashFormatter) end it "builds :custom style logger" do CustomFormatter = Class.new(HTTParty::Logger::CurlFormatter) HTTParty::Logger.add_formatter(:custom, CustomFormatter) logger_double = double expect(subject.build(logger_double, nil, :custom)). to be_an_instance_of(CustomFormatter) end it "raises error when formatter exists" do CustomFormatter2= Class.new(HTTParty::Logger::CurlFormatter) HTTParty::Logger.add_formatter(:custom2, CustomFormatter2) expect{ HTTParty::Logger.add_formatter(:custom2, CustomFormatter2) }. to raise_error HTTParty::Error end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/logger/logstash_formatter_spec.rb
spec/httparty/logger/logstash_formatter_spec.rb
require 'json' require 'spec_helper' RSpec.describe HTTParty::Logger::LogstashFormatter do let(:severity) { :info } let(:http_method) { 'GET' } let(:path) { 'http://my.domain.com/my_path' } let(:logger_double) { double('Logger') } let(:request_double) { double('Request', http_method: Net::HTTP::Get, path: "#{path}") } let(:request_time) { Time.new.strftime("%Y-%m-%d %H:%M:%S %z") } let(:log_message) do { '@timestamp' => request_time, '@version' => 1, 'content_length' => content_length || '-', 'http_method' => http_method, 'message' => message, 'path' => path, 'response_code' => response_code, 'severity' => severity, 'tags' => ['HTTParty'], }.to_json end subject { described_class.new(logger_double, severity) } before do expect(logger_double).to receive(:info).with(log_message) end describe "#format" do let(:response_code) { 302 } let(:content_length) { '-' } let(:message) { "[HTTParty] #{response_code} \"#{http_method} #{path}\" #{content_length} " } it "formats a response to be compatible with Logstash" do response_double = double( code: response_code, :[] => nil ) subject.format(request_double, response_double) end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/request/streaming_multipart_body_spec.rb
spec/httparty/request/streaming_multipart_body_spec.rb
require 'spec_helper' require 'tempfile' RSpec.describe HTTParty::Request::StreamingMultipartBody do let(:boundary) { '------------------------c772861a5109d5ef' } describe '#read' do context 'with a simple file' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:parts) { [['avatar', file, true]] } subject { described_class.new(parts, boundary) } after { file.close } it 'streams the complete multipart body' do result = subject.read expect(result.encoding).to eq(Encoding::BINARY) expect(result).to include("--#{boundary}") expect(result).to include('Content-Disposition: form-data; name="avatar"') expect(result).to include('filename="tiny.gif"') expect(result).to include('Content-Type: image/gif') expect(result).to include("GIF89a") # GIF file header expect(result).to end_with("--#{boundary}--\r\n") end it 'returns same content as non-streaming body' do # Create equivalent Body for comparison body = HTTParty::Request::Body.new({ avatar: File.open('spec/fixtures/tiny.gif', 'rb') }) allow(HTTParty::Request::MultipartBoundary).to receive(:generate).and_return(boundary) streaming_result = subject.read non_streaming_result = body.call expect(streaming_result).to eq(non_streaming_result) end end context 'with mixed file and text fields' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:parts) do [ ['user[avatar]', file, true], ['user[name]', 'John Doe', false], ['user[active]', 'true', false] ] end subject { described_class.new(parts, boundary) } after { file.close } it 'streams all parts correctly' do result = subject.read expect(result).to include('name="user[avatar]"') expect(result).to include('name="user[name]"') expect(result).to include('John Doe') expect(result).to include('name="user[active]"') expect(result).to include('true') end end context 'reading in chunks' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:parts) { [['avatar', file, true]] } subject { described_class.new(parts, boundary) } after { file.close } it 'reads correctly in small chunks' do chunks = [] while (chunk = subject.read(10)) chunks << chunk end full_result = chunks.join subject.rewind single_read = subject.read expect(full_result).to eq(single_read) end it 'returns nil when exhausted' do subject.read # Read all expect(subject.read).to be_nil end end end describe '#size' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:parts) { [['avatar', file, true]] } subject { described_class.new(parts, boundary) } after { file.close } it 'returns the correct total size' do size = subject.size content = subject.read expect(size).to eq(content.bytesize) end end describe '#rewind' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:parts) { [['avatar', file, true]] } subject { described_class.new(parts, boundary) } after { file.close } it 'allows re-reading the stream' do first_read = subject.read subject.rewind second_read = subject.read expect(first_read).to eq(second_read) end end describe 'memory efficiency' do it 'does not load entire file into memory at once' do # Create a larger temp file tempfile = Tempfile.new(['large', '.bin']) tempfile.write('x' * (1024 * 1024)) # 1 MB tempfile.rewind parts = [['file', tempfile, true]] stream = described_class.new(parts, boundary) # Read in small chunks - this should work without allocating 1MB at once chunks_read = 0 while stream.read(1024) chunks_read += 1 end expect(chunks_read).to be > 100 # Should have read many chunks tempfile.close tempfile.unlink end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/spec/httparty/request/body_spec.rb
spec/httparty/request/body_spec.rb
require 'spec_helper' require 'tempfile' RSpec.describe HTTParty::Request::Body do describe '#call' do let(:options) { {} } subject { described_class.new(params, **options).call } context 'when params is string' do let(:params) { 'name=Bob%20Jones' } it { is_expected.to eq params } end context 'when params is hash' do let(:params) { { people: ["Bob Jones", "Mike Smith"] } } let(:converted_params) { "people%5B%5D=Bob%20Jones&people%5B%5D=Mike%20Smith"} it { is_expected.to eq converted_params } context 'when params has file' do before do allow(HTTParty::Request::MultipartBoundary) .to receive(:generate).and_return("------------------------c772861a5109d5ef") end let(:file) { File.open('spec/fixtures/tiny.gif') } let(:params) do { user: { avatar: file, first_name: 'John', last_name: 'Doe', enabled: true } } end let(:expected_file_name) { 'tiny.gif' } let(:expected_file_contents) { "GIF89a\u0001\u0000\u0001\u0000\u0000\xFF\u0000,\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0000\u0002\u0000;" } let(:expected_content_type) { 'image/gif' } let(:multipart_params) do ("--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"#{expected_file_name}\"\r\n" \ "Content-Type: #{expected_content_type}\r\n" \ "\r\n" \ "#{expected_file_contents}\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[first_name]\"\r\n" \ "\r\n" \ "John\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[last_name]\"\r\n" \ "\r\n" \ "Doe\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[enabled]\"\r\n" \ "\r\n" \ "true\r\n" \ "--------------------------c772861a5109d5ef--\r\n").b end it { is_expected.to eq multipart_params } it { expect { subject }.not_to change { file.pos } } context 'when passing multipart as an option' do let(:options) { { force_multipart: true } } let(:params) do { user: { first_name: 'John', last_name: 'Doe', enabled: true } } end let(:multipart_params) do ("--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[first_name]\"\r\n" \ "\r\n" \ "John\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[last_name]\"\r\n" \ "\r\n" \ "Doe\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[enabled]\"\r\n" \ "\r\n" \ "true\r\n" \ "--------------------------c772861a5109d5ef--\r\n").b end it { is_expected.to eq multipart_params } end context 'file object responds to original_filename' do let(:some_temp_file) { Tempfile.new(['some_temp_file','.gif']) } let(:expected_file_name) { "some_temp_file.gif" } let(:expected_file_contents) { "Hello" } let(:file) { double(:mocked_action_dispatch, path: some_temp_file.path, original_filename: 'some_temp_file.gif', read: expected_file_contents) } before { some_temp_file.write('Hello') } it { is_expected.to eq multipart_params } end context 'when file name contains [ " \r \n ]' do let(:options) { { force_multipart: true } } let(:some_temp_file) { Tempfile.new(['basefile', '.txt']) } let(:file_content) { 'test' } let(:raw_filename) { "dummy=tampering.sh\"; \r\ndummy=a.txt" } let(:expected_file_name) { 'dummy=tampering.sh%22; %0D%0Adummy=a.txt' } let(:file) { double(:mocked_action_dispatch, path: some_temp_file.path, original_filename: raw_filename, read: file_content) } let(:params) do { user: { attachment_file: file, enabled: true } } end let(:multipart_params) do ("--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[attachment_file]\"; filename=\"#{expected_file_name}\"\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "test\r\n" \ "--------------------------c772861a5109d5ef\r\n" \ "Content-Disposition: form-data; name=\"user[enabled]\"\r\n" \ "\r\n" \ "true\r\n" \ "--------------------------c772861a5109d5ef--\r\n").b end it { is_expected.to eq multipart_params } end context 'when file is binary data and params contain non-ascii characters' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } let(:params) do { user: "Jöhn Döé", enabled: true, avatar: file, } end it 'does not raise encoding errors' do expect { subject }.not_to raise_error end it 'produces valid binary multipart body' do result = subject expect(result.encoding).to eq(Encoding::BINARY) expect(result).to include("Jöhn Döé".b) end it 'concatenates binary file data with UTF-8 text without corruption' do result = subject # Should contain both the UTF-8 user field and binary GIF data expect(result).to include('Content-Disposition: form-data; name="user"'.b) expect(result).to include("Jöhn Döé".b) expect(result).to include('Content-Disposition: form-data; name="avatar"'.b) expect(result).to include("GIF89a".b) # GIF file header end end end end end describe '#multipart?' do let(:force_multipart) { false } let(:file) { File.open('spec/fixtures/tiny.gif') } subject { described_class.new(params, force_multipart: force_multipart).multipart? } context 'when params does not respond to to_hash' do let(:params) { 'name=Bob%20Jones' } it { is_expected.to be false } end context 'when params responds to to_hash' do class HashLike def initialize(hash) @hash = hash end def to_hash @hash end end class ArrayLike def initialize(ary) @ary = ary end def to_ary @ary end end context 'when force_multipart is true' do let(:params) { { name: 'Bob Jones' } } let(:force_multipart) { true } it { is_expected.to be true } end context 'when it does not contain a file' do let(:hash_like_param) { HashLike.new(first: 'Bob', last: ArrayLike.new(['Jones'])) } let(:params) { { name: ArrayLike.new([hash_like_param]) } } it { is_expected.to eq false } end context 'when it contains file' do let(:hash_like_param) { HashLike.new(first: 'Bob', last: 'Jones', file: ArrayLike.new([file])) } let(:params) { { name: ArrayLike.new([hash_like_param]) } } it { is_expected.to be true } end end end describe '#streaming?' do let(:file) { File.open('spec/fixtures/tiny.gif') } after { file.close } context 'when params contains a file' do let(:params) { { avatar: file } } subject { described_class.new(params) } it { expect(subject.streaming?).to be true } end context 'when force_multipart but no file' do let(:params) { { name: 'John' } } subject { described_class.new(params, force_multipart: true) } it { expect(subject.streaming?).to be false } end context 'when params is a string' do let(:params) { 'name=John' } subject { described_class.new(params) } it { expect(subject.streaming?).to be false } end end describe '#to_stream' do let(:file) { File.open('spec/fixtures/tiny.gif', 'rb') } after { file.close } context 'when streaming is possible' do let(:params) { { avatar: file } } subject { described_class.new(params) } it 'returns a StreamingMultipartBody' do expect(subject.to_stream).to be_a(HTTParty::Request::StreamingMultipartBody) end it 'produces equivalent content to call' do allow(HTTParty::Request::MultipartBoundary).to receive(:generate).and_return('test-boundary') stream = subject.to_stream file.rewind streamed_content = stream.read file.rewind body = described_class.new(params) allow(HTTParty::Request::MultipartBoundary).to receive(:generate).and_return('test-boundary') regular_content = body.call expect(streamed_content).to eq(regular_content) end end context 'when streaming is not possible' do let(:params) { { name: 'John' } } subject { described_class.new(params, force_multipart: true) } it 'returns nil' do expect(subject.to_stream).to be_nil end end end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/rubyurl.rb
examples/rubyurl.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class Rubyurl include HTTParty base_uri 'rubyurl.com' def self.shorten(website_url) post('/api/links.json', query: { link: { website_url: website_url } }) end end pp Rubyurl.shorten('http://istwitterdown.com/')
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/custom_parsers.rb
examples/custom_parsers.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class ParseAtom include HTTParty # Support Atom along with the default parsers: xml, json, etc. class Parser::Atom < HTTParty::Parser SupportedFormats.merge!({"application/atom+xml" => :atom}) protected # perform atom parsing on body def atom body.to_atom end end parser Parser::Atom end class OnlyParseAtom include HTTParty # Only support Atom class Parser::OnlyAtom < HTTParty::Parser SupportedFormats = { "application/atom+xml" => :atom } protected # perform atom parsing on body def atom body.to_atom end end parser Parser::OnlyAtom end class SkipParsing include HTTParty # Parse the response body however you like class Parser::Simple < HTTParty::Parser def parse body end end parser Parser::Simple end class AdHocParsing include HTTParty parser( proc do |body, format| case format when :json body.to_json when :xml body.to_xml else body end end ) end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/logging.rb
examples/logging.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'logger' require 'pp' my_logger = Logger.new STDOUT my_logger.info "Logging can be used on the main HTTParty class. It logs redirects too." HTTParty.get "http://google.com", logger: my_logger my_logger.info '*' * 70 my_logger.info "It can be used also on a custom class." class Google include HTTParty logger ::Logger.new STDOUT end Google.get "http://google.com" my_logger.info '*' * 70 my_logger.info "The default formatter is :apache. The :curl formatter can also be used." my_logger.info "You can tell which method to call on the logger too. It is info by default." HTTParty.get "http://google.com", logger: my_logger, log_level: :debug, log_format: :curl my_logger.info '*' * 70 my_logger.info "These configs are also available on custom classes." class Google include HTTParty logger ::Logger.new(STDOUT), :debug, :curl end Google.get "http://google.com"
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/headers_and_user_agents.rb
examples/headers_and_user_agents.rb
# To send custom user agents to identify your application to a web service (or mask as a specific browser for testing), send "User-Agent" as a hash to headers as shown below. dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' response = HTTParty.get('http://example.com', { headers: {"User-Agent" => "Httparty"}, debug_output: STDOUT, # To show that User-Agent is Httparty })
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/microsoft_graph.rb
examples/microsoft_graph.rb
require 'httparty' class MicrosoftGraph MS_BASE_URL = "https://login.microsoftonline.com".freeze TOKEN_REQUEST_PATH = "oauth2/v2.0/token".freeze def initialize(tenant_id) @tenant_id = tenant_id end # Make a request to the Microsoft Graph API, for instance https://graph.microsoft.com/v1.0/users def request(url) return false unless (token = bearer_token) response = HTTParty.get( url, headers: { Authorization: "Bearer #{token}" } ) return false unless response.code == 200 return JSON.parse(response.body) end private # A post to the Microsoft Graph to get a bearer token for the specified tenant. In this example # our Rails application has already been given permission to request these tokens by the admin of # the specified tenant_id. # # See here for more information https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service # # This request also makes use of the multipart/form-data post body. def bearer_token response = HTTParty.post( "#{MS_BASE_URL}/#{@tenant_id}/#{TOKEN_REQUEST_PATH}", multipart: true, body: { client_id: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_id], client_secret: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_secret], scope: 'https://graph.microsoft.com/.default', grant_type: 'client_credentials' } ) return false unless response.code == 200 JSON.parse(response.body)['access_token'] end end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/party_foul_mode.rb
examples/party_foul_mode.rb
require 'httparty' class APIClient include HTTParty base_uri 'api.example.com' def self.fetch_user(id) begin get("/users/#{id}", foul: true) rescue HTTParty::NetworkError => e handle_network_error(e) rescue HTTParty::ResponseError => e handle_api_error(e) end end private def self.handle_network_error(error) case error.cause when Errno::ECONNREFUSED { error: :server_down, message: "The API server appears to be down", details: error.message } when Net::OpenTimeout, Timeout::Error { error: :timeout, message: "The request timed out", details: error.message } when SocketError { error: :network_error, message: "Could not connect to the API server", details: error.message } when OpenSSL::SSL::SSLError { error: :ssl_error, message: "SSL certificate verification failed", details: error.message } else { error: :unknown_network_error, message: "An unexpected network error occurred", details: error.message } end end def self.handle_api_error(error) { error: :api_error, message: "API returned error #{error.response.code}", details: error.response.body } end end # Example usage: # 1. When server is down result = APIClient.fetch_user(123) puts "Server down example:" puts result.inspect puts # 2. When request times out result = APIClient.fetch_user(456) puts "Timeout example:" puts result.inspect puts # 3. When SSL error occurs result = APIClient.fetch_user(789) puts "SSL error example:" puts result.inspect puts # 4. Simple example without a wrapper class begin HTTParty.get('https://api.example.com/users', foul: true) rescue HTTParty::Foul => e puts "Direct usage example:" puts "Error type: #{e.cause.class}" puts "Error message: #{e.message}" end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/twitter.rb
examples/twitter.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' config = YAML.load(File.read(File.join(ENV['HOME'], '.twitter'))) class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {username: u, password: p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which = :friends, options = {}) options.merge!({ basic_auth: @auth }) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { query: { status: text }, basic_auth: @auth } self.class.post('/statuses/update.json', options) end end twitter = Twitter.new(config['email'], config['password']) pp twitter.timeline # pp twitter.timeline(:friends, query: {since_id: 868482746}) # pp twitter.timeline(:friends, query: 'since_id=868482746') # pp twitter.post('this is a test of 0.2.0')
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/peer_cert.rb
examples/peer_cert.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') peer_cert = nil HTTParty.get("https://www.example.com") do |fragment| peer_cert ||= fragment.connection.peer_cert end puts "The server's certificate expires #{peer_cert.not_after}"
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/google.rb
examples/google.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class Google include HTTParty format :html end # google.com redirects to www.google.com so this is live test for redirection pp Google.get('http://google.com') puts '', '*' * 70, '' # check that ssl is requesting right pp Google.get('https://www.google.com')
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/basic.rb
examples/basic.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' # You can also use post, put, delete, head, options in the same fashion response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow') puts response.body, response.code, response.message, response.headers.inspect # An example post to a minimal rails app in the development environment # Note that "skip_before_filter :verify_authenticity_token" must be set in the # "pears" controller for this example class Partay include HTTParty base_uri 'http://localhost:3000' end options = { body: { pear: { # your resource foo: '123', # your columns/data bar: 'second', baz: 'last thing' } } } pp Partay.post('/pears.xml', options)
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/stream_download.rb
examples/stream_download.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' # download file linux-4.6.4.tar.xz without using the memory response = nil filename = "linux-4.6.4.tar.xz" url = "https://cdn.kernel.org/pub/linux/kernel/v4.x/#{filename}" File.open(filename, "w") do |file| response = HTTParty.get(url, stream_body: true) do |fragment| if [301, 302].include?(fragment.code) print "skip writing for redirect" elsif fragment.code == 200 print "." file.write(fragment) else raise StandardError, "Non-success status code while streaming #{fragment.code}" end end end puts pp "Success: #{response.success?}" pp File.stat(filename).inspect File.unlink(filename)
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/whoismyrep.rb
examples/whoismyrep.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class Rep include HTTParty end pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544') pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: { zip: 46544 })
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/tripit_sign_in.rb
examples/tripit_sign_in.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') class TripIt include HTTParty base_uri 'https://www.tripit.com' debug_output def initialize(email, password) @email = email get_response = self.class.get('/account/login') get_response_cookie = parse_cookie(get_response.headers['Set-Cookie']) post_response = self.class.post( '/account/login', body: { login_email_address: email, login_password: password }, headers: {'Cookie' => get_response_cookie.to_cookie_string } ) @cookie = parse_cookie(post_response.headers['Set-Cookie']) end def account_settings self.class.get('/account/edit', headers: { 'Cookie' => @cookie.to_cookie_string }) end def logged_in? account_settings.include? "You're logged in as #{@email}" end private def parse_cookie(resp) cookie_hash = CookieHash.new resp.get_fields('Set-Cookie').each { |c| cookie_hash.add_cookies(c) } cookie_hash end end tripit = TripIt.new('email', 'password') puts "Logged in: #{tripit.logged_in?}"
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/crack.rb
examples/crack.rb
require 'rubygems' require 'crack' dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class Rep include HTTParty parser( proc do |body, format| Crack::XML.parse(body) end ) end pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544') pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: { zip: 46544 })
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/aaws.rb
examples/aaws.rb
require 'rubygems' require 'active_support' require 'active_support/core_ext/hash' require 'active_support/core_ext/string' dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' config = YAML.load(File.read(File.join(ENV['HOME'], '.aaws'))) module AAWS class Book include HTTParty base_uri 'http://ecs.amazonaws.com' default_params Service: 'AWSECommerceService', Operation: 'ItemSearch', SearchIndex: 'Books' def initialize(key) @auth = { AWSAccessKeyId: key } end def search(options = {}) raise ArgumentError, 'You must search for something' if options[:query].blank? # amazon uses nasty camelized query params options[:query] = options[:query] .reverse_merge(@auth) .transform_keys { |k| k.to_s.camelize } # make a request and return the items (NOTE: this doesn't handle errors at this point) self.class.get('/onca/xml', options)['ItemSearchResponse']['Items'] end end end aaws = AAWS::Book.new(config[:access_key]) pp aaws.search(query: { title: 'Ruby On Rails' })
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/rescue_json.rb
examples/rescue_json.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') # Take note of the "; 1" at the end of the following line. It's required only if # running this in IRB, because IRB will try to inspect the variable named # "request", triggering the exception. request = HTTParty.get 'https://rubygems.org/api/v1/versions/doesnotexist.json' ; 1 # Check an exception due to parsing the response # because HTTParty evaluate the response lazily begin request.inspect # This would also suffice by forcing the request to be parsed: # request.parsed_response rescue => e puts "Rescued #{e.inspect}" end
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/body_stream.rb
examples/body_stream.rb
# To upload file to a server use :body_stream HTTParty.put( 'http://localhost:3000/train', body_stream: File.open('sample_configs/config_train_server_md.yml', 'r') ) # Actually, it works with any IO object HTTParty.put( 'http://localhost:3000/train', body_stream: StringIO.new('foo') )
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/stackexchange.rb
examples/stackexchange.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class StackExchange include HTTParty base_uri 'api.stackexchange.com' def initialize(service, page) @options = { query: { site: service, page: page } } end def questions self.class.get("/2.2/questions", @options) end def users self.class.get("/2.2/users", @options) end end stack_exchange = StackExchange.new("stackoverflow", 1) pp stack_exchange.questions pp stack_exchange.users
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/idn.rb
examples/idn.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class Idn include HTTParty uri_adapter Addressable::URI end pp Idn.get("https://i❤️.ws/emojidomain/💎?format=json")
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/delicious.rb
examples/delicious.rb
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' config = YAML.load(File.read(File.join(ENV['HOME'], '.delicious'))) class Delicious include HTTParty base_uri 'https://api.del.icio.us/v1' def initialize(u, p) @auth = { username: u, password: p } end # query params that filter the posts are: # tag (optional). Filter by this tag. # dt (optional). Filter by this date (CCYY-MM-DDThh:mm:ssZ). # url (optional). Filter by this url. # ie: posts(query: {tag: 'ruby'}) def posts(options = {}) options.merge!({ basic_auth: @auth }) self.class.get('/posts/get', options) end # query params that filter the posts are: # tag (optional). Filter by this tag. # count (optional). Number of items to retrieve (Default:15, Maximum:100). def recent(options = {}) options.merge!({ basic_auth: @auth }) self.class.get('/posts/recent', options) end end delicious = Delicious.new(config['username'], config['password']) pp delicious.posts(query: { tag: 'ruby' }) pp delicious.recent delicious.recent['posts']['post'].each { |post| puts post['href'] }
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/multipart.rb
examples/multipart.rb
# If you are uploading file in params, multipart will used as content-type automatically HTTParty.post( 'http://localhost:3000/user', body: { name: 'Foo Bar', email: 'example@email.com', avatar: File.open('/full/path/to/avatar.jpg') } ) # However, you can force it yourself HTTParty.post( 'http://localhost:3000/user', multipart: true, body: { name: 'Foo Bar', email: 'example@email.com' } )
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/examples/nokogiri_html_parser.rb
examples/nokogiri_html_parser.rb
require 'rubygems' require 'nokogiri' dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require File.join(dir, 'httparty') require 'pp' class HtmlParserIncluded < HTTParty::Parser def html Nokogiri::HTML(body) end end class Page include HTTParty parser HtmlParserIncluded end pp Page.get('http://www.google.com')
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false
jnunemaker/httparty
https://github.com/jnunemaker/httparty/blob/55ec76e8d1df7903eab3f7c2367991400d3cf65e/lib/httparty.rb
lib/httparty.rb
# frozen_string_literal: true require 'pathname' require 'net/http' require 'uri' require 'httparty/module_inheritable_attributes' require 'httparty/cookie_hash' require 'httparty/net_digest_auth' require 'httparty/version' require 'httparty/connection_adapter' require 'httparty/logger/logger' require 'httparty/request/body' require 'httparty/response_fragment' require 'httparty/decompressor' require 'httparty/text_encoder' require 'httparty/headers_processor' # @see HTTParty::ClassMethods module HTTParty def self.included(base) base.extend ClassMethods base.send :include, ModuleInheritableAttributes base.send(:mattr_inheritable, :default_options) base.send(:mattr_inheritable, :default_cookies) base.instance_variable_set(:@default_options, {}) base.instance_variable_set(:@default_cookies, CookieHash.new) end # == Common Request Options # Request methods (get, post, patch, put, delete, head, options) all take a common set of options. These are: # # [:+body+:] Body of the request. If passed an object that responds to #to_hash, will try to normalize it first, by default passing it to ActiveSupport::to_params. Any other kind of object will get used as-is. # [:+http_proxyaddr+:] Address of proxy server to use. # [:+http_proxyport+:] Port of proxy server to use. # [:+http_proxyuser+:] User for proxy server authentication. # [:+http_proxypass+:] Password for proxy server authentication. # [:+limit+:] Maximum number of redirects to follow. Takes precedences over :+no_follow+. # [:+query+:] Query string, or an object that responds to #to_hash representing it. Normalized according to the same rules as :+body+. If you specify this on a POST, you must use an object which responds to #to_hash. See also HTTParty::ClassMethods.default_params. # [:+timeout+:] Timeout for opening connection and reading data. # [:+local_host+:] Local address to bind to before connecting. # [:+local_port+:] Local port to bind to before connecting. # [:+body_stream+:] Allow streaming to a REST server to specify a body_stream. # [:+stream_body+:] Allow for streaming large files without loading them into memory. # [:+multipart+:] Force content-type to be multipart # # There are also another set of options with names corresponding to various class methods. The methods in question are those that let you set a class-wide default, and the options override the defaults on a request-by-request basis. Those options are: # * :+base_uri+: see HTTParty::ClassMethods.base_uri. # * :+basic_auth+: see HTTParty::ClassMethods.basic_auth. Only one of :+basic_auth+ and :+digest_auth+ can be used at a time; if you try using both, you'll get an ArgumentError. # * :+debug_output+: see HTTParty::ClassMethods.debug_output. # * :+digest_auth+: see HTTParty::ClassMethods.digest_auth. Only one of :+basic_auth+ and :+digest_auth+ can be used at a time; if you try using both, you'll get an ArgumentError. # * :+format+: see HTTParty::ClassMethods.format. # * :+headers+: see HTTParty::ClassMethods.headers. Must be a an object which responds to #to_hash. # * :+maintain_method_across_redirects+: see HTTParty::ClassMethods.maintain_method_across_redirects. # * :+no_follow+: see HTTParty::ClassMethods.no_follow. # * :+parser+: see HTTParty::ClassMethods.parser. # * :+uri_adapter+: see HTTParty::ClassMethods.uri_adapter # * :+connection_adapter+: see HTTParty::ClassMethods.connection_adapter. # * :+pem+: see HTTParty::ClassMethods.pem. # * :+query_string_normalizer+: see HTTParty::ClassMethods.query_string_normalizer # * :+ssl_ca_file+: see HTTParty::ClassMethods.ssl_ca_file. # * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path. module ClassMethods # Turns on or off the foul option. # # class Foo # include HTTParty # foul true # end def foul(bool) default_options[:foul] = bool end # Turns on logging # # class Foo # include HTTParty # logger Logger.new('http_logger'), :info, :apache # end def logger(logger, level = :info, format = :apache) default_options[:logger] = logger default_options[:log_level] = level default_options[:log_format] = format end # Raises HTTParty::ResponseError if response's code matches this statuses # # class Foo # include HTTParty # raise_on [404, 500, '5[0-9]*'] # end def raise_on(codes = []) default_options[:raise_on] = *codes end # Allows setting http proxy information to be used # # class Foo # include HTTParty # http_proxy 'http://foo.com', 80, 'user', 'pass' # end def http_proxy(addr = nil, port = nil, user = nil, pass = nil) default_options[:http_proxyaddr] = addr default_options[:http_proxyport] = port default_options[:http_proxyuser] = user default_options[:http_proxypass] = pass end # Allows setting a base uri to be used for each request. # Will normalize uri to include http, etc. # # class Foo # include HTTParty # base_uri 'twitter.com' # end def base_uri(uri = nil) return default_options[:base_uri] unless uri default_options[:base_uri] = HTTParty.normalize_base_uri(uri) end # Allows setting basic authentication username and password. # # class Foo # include HTTParty # basic_auth 'username', 'password' # end def basic_auth(u, p) default_options[:basic_auth] = {username: u, password: p} end # Allows setting digest authentication username and password. # # class Foo # include HTTParty # digest_auth 'username', 'password' # end def digest_auth(u, p) default_options[:digest_auth] = {username: u, password: p} end # Do not send rails style query strings. # Specifically, don't use bracket notation when sending an array # # For a query: # get '/', query: {selected_ids: [1,2,3]} # # The default query string looks like this: # /?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3 # # Call `disable_rails_query_string_format` to transform the query string # into: # /?selected_ids=1&selected_ids=2&selected_ids=3 # # @example # class Foo # include HTTParty # disable_rails_query_string_format # end def disable_rails_query_string_format query_string_normalizer Request::NON_RAILS_QUERY_STRING_NORMALIZER end # Allows setting default parameters to be appended to each request. # Great for api keys and such. # # class Foo # include HTTParty # default_params api_key: 'secret', another: 'foo' # end def default_params(h = {}) raise ArgumentError, 'Default params must be an object which responds to #to_hash' unless h.respond_to?(:to_hash) default_options[:default_params] ||= {} default_options[:default_params].merge!(h) end # Allows setting a default timeout for all HTTP calls # Timeout is specified in seconds. # # class Foo # include HTTParty # default_timeout 10 # end def default_timeout(value) validate_timeout_argument(__method__, value) default_options[:timeout] = value end # Allows setting a default open_timeout for all HTTP calls in seconds # # class Foo # include HTTParty # open_timeout 10 # end def open_timeout(value) validate_timeout_argument(__method__, value) default_options[:open_timeout] = value end # Allows setting a default read_timeout for all HTTP calls in seconds # # class Foo # include HTTParty # read_timeout 10 # end def read_timeout(value) validate_timeout_argument(__method__, value) default_options[:read_timeout] = value end # Allows setting a default write_timeout for all HTTP calls in seconds # Supported by Ruby > 2.6.0 # # class Foo # include HTTParty # write_timeout 10 # end def write_timeout(value) validate_timeout_argument(__method__, value) default_options[:write_timeout] = value end # Set an output stream for debugging, defaults to $stderr. # The output stream is passed on to Net::HTTP#set_debug_output. # # class Foo # include HTTParty # debug_output $stderr # end def debug_output(stream = $stderr) default_options[:debug_output] = stream end # Allows setting HTTP headers to be used for each request. # # class Foo # include HTTParty # headers 'Accept' => 'text/html' # end def headers(h = nil) if h raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash) default_options[:headers] ||= {} default_options[:headers].merge!(h.to_hash) else default_options[:headers] || {} end end def cookies(h = {}) raise ArgumentError, 'Cookies must be an object which responds to #to_hash' unless h.respond_to?(:to_hash) default_cookies.add_cookies(h) end # Proceed to the location header when an HTTP response dictates a redirect. # Redirects are always followed by default. # # @example # class Foo # include HTTParty # base_uri 'http://google.com' # follow_redirects true # end def follow_redirects(value = true) default_options[:follow_redirects] = value end # Allows setting the format with which to parse. # Must be one of the allowed formats ie: json, xml # # class Foo # include HTTParty # format :json # end def format(f = nil) if f.nil? default_options[:format] else parser(Parser) if parser.nil? default_options[:format] = f validate_format end end # Declare whether or not to follow redirects. When true, an # {HTTParty::RedirectionTooDeep} error will raise upon encountering a # redirect. You can then gain access to the response object via # HTTParty::RedirectionTooDeep#response. # # @see HTTParty::ResponseError#response # # @example # class Foo # include HTTParty # base_uri 'http://google.com' # no_follow true # end # # begin # Foo.get('/') # rescue HTTParty::RedirectionTooDeep => e # puts e.response.body # end def no_follow(value = false) default_options[:no_follow] = value end # Declare that you wish to maintain the chosen HTTP method across redirects. # The default behavior is to follow redirects via the GET method, except # if you are making a HEAD request, in which case the default is to # follow all redirects with HEAD requests. # If you wish to maintain the original method, you can set this option to true. # # @example # class Foo # include HTTParty # base_uri 'http://google.com' # maintain_method_across_redirects true # end def maintain_method_across_redirects(value = true) default_options[:maintain_method_across_redirects] = value end # Declare that you wish to resend the full HTTP request across redirects, # even on redirects that should logically become GET requests. # A 303 redirect in HTTP signifies that the redirected url should normally # retrieved using a GET request, for instance, it is the output of a previous # POST. maintain_method_across_redirects respects this behavior, but you # can force HTTParty to resend_on_redirect even on 303 responses. # # @example # class Foo # include HTTParty # base_uri 'http://google.com' # resend_on_redirect # end def resend_on_redirect(value = true) default_options[:resend_on_redirect] = value end # Allows setting a PEM file to be used # # class Foo # include HTTParty # pem File.read('/home/user/my.pem'), "optional password" # end def pem(pem_contents, password = nil) default_options[:pem] = pem_contents default_options[:pem_password] = password end # Allows setting a PKCS12 file to be used # # class Foo # include HTTParty # pkcs12 File.read('/home/user/my.p12'), "password" # end def pkcs12(p12_contents, password) default_options[:p12] = p12_contents default_options[:p12_password] = password end # Override the way query strings are normalized. # Helpful for overriding the default rails normalization of Array queries. # # For a query: # get '/', query: {selected_ids: [1,2,3]} # # The default query string normalizer returns: # /?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3 # # Let's change it to this: # /?selected_ids=1&selected_ids=2&selected_ids=3 # # Pass a Proc to the query normalizer which accepts the yielded query. # # @example Modifying Array query strings # class ServiceWrapper # include HTTParty # # query_string_normalizer proc { |query| # query.map do |key, value| # value.map {|v| "#{key}=#{v}"} # end.join('&') # } # end # # @param [Proc] normalizer custom query string normalizer. # @yield [Hash, String] query string # @yieldreturn [Array] an array that will later be joined with '&' def query_string_normalizer(normalizer) default_options[:query_string_normalizer] = normalizer end # Allows setting of SSL version to use. This only works in Ruby 1.9+. # You can get a list of valid versions from OpenSSL::SSL::SSLContext::METHODS. # # class Foo # include HTTParty # ssl_version :SSLv3 # end def ssl_version(version) default_options[:ssl_version] = version end # Deactivate automatic decompression of the response body. # This will require you to explicitly handle body decompression # by inspecting the Content-Encoding response header. # # Refer to docs/README.md "HTTP Compression" section for # further details. # # @example # class Foo # include HTTParty # skip_decompression # end def skip_decompression(value = true) default_options[:skip_decompression] = !!value end # Allows setting of SSL ciphers to use. This only works in Ruby 1.9+. # You can get a list of valid specific ciphers from OpenSSL::Cipher.ciphers. # You also can specify a cipher suite here, listed here at openssl.org: # http://www.openssl.org/docs/apps/ciphers.html#CIPHER_SUITE_NAMES # # class Foo # include HTTParty # ciphers "RC4-SHA" # end def ciphers(cipher_names) default_options[:ciphers] = cipher_names end # Allows setting an OpenSSL certificate authority file. The file # should contain one or more certificates in PEM format. # # Setting this option enables certificate verification. All # certificates along a chain must be available in ssl_ca_file or # ssl_ca_path for verification to succeed. # # # class Foo # include HTTParty # ssl_ca_file '/etc/ssl/certs/ca-certificates.crt' # end def ssl_ca_file(path) default_options[:ssl_ca_file] = path end # Allows setting an OpenSSL certificate authority path (directory). # # Setting this option enables certificate verification. All # certificates along a chain must be available in ssl_ca_file or # ssl_ca_path for verification to succeed. # # class Foo # include HTTParty # ssl_ca_path '/etc/ssl/certs/' # end def ssl_ca_path(path) default_options[:ssl_ca_path] = path end # Allows setting a custom parser for the response. # # class Foo # include HTTParty # parser Proc.new {|data| ...} # end def parser(custom_parser = nil) if custom_parser.nil? default_options[:parser] else default_options[:parser] = custom_parser validate_format end end # Allows setting a custom URI adapter. # # class Foo # include HTTParty # uri_adapter Addressable::URI # end def uri_adapter(uri_adapter) raise ArgumentError, 'The URI adapter should respond to #parse' unless uri_adapter.respond_to?(:parse) default_options[:uri_adapter] = uri_adapter end # Allows setting a custom connection_adapter for the http connections # # @example # class Foo # include HTTParty # connection_adapter Proc.new {|uri, options| ... } # end # # @example provide optional configuration for your connection_adapter # class Foo # include HTTParty # connection_adapter Proc.new {|uri, options| ... }, {foo: :bar} # end # # @see HTTParty::ConnectionAdapter def connection_adapter(custom_adapter = nil, options = nil) if custom_adapter.nil? default_options[:connection_adapter] else default_options[:connection_adapter] = custom_adapter default_options[:connection_adapter_options] = options end end # Allows making a get request to a url. # # class Foo # include HTTParty # end # # # Simple get with full url # Foo.get('http://foo.com/resource.json') # # # Simple get with full url and query parameters # # ie: http://foo.com/resource.json?limit=10 # Foo.get('http://foo.com/resource.json', query: {limit: 10}) def get(path, options = {}, &block) perform_request Net::HTTP::Get, path, options, &block end # Allows making a post request to a url. # # class Foo # include HTTParty # end # # # Simple post with full url and setting the body # Foo.post('http://foo.com/resources', body: {bar: 'baz'}) # # # Simple post with full url using :query option, # # which appends the parameters to the URI. # Foo.post('http://foo.com/resources', query: {bar: 'baz'}) def post(path, options = {}, &block) perform_request Net::HTTP::Post, path, options, &block end # Perform a PATCH request to a path def patch(path, options = {}, &block) perform_request Net::HTTP::Patch, path, options, &block end # Perform a PUT request to a path def put(path, options = {}, &block) perform_request Net::HTTP::Put, path, options, &block end # Perform a DELETE request to a path def delete(path, options = {}, &block) perform_request Net::HTTP::Delete, path, options, &block end # Perform a MOVE request to a path def move(path, options = {}, &block) perform_request Net::HTTP::Move, path, options, &block end # Perform a COPY request to a path def copy(path, options = {}, &block) perform_request Net::HTTP::Copy, path, options, &block end # Perform a HEAD request to a path def head(path, options = {}, &block) ensure_method_maintained_across_redirects options perform_request Net::HTTP::Head, path, options, &block end # Perform an OPTIONS request to a path def options(path, options = {}, &block) perform_request Net::HTTP::Options, path, options, &block end # Perform a MKCOL request to a path def mkcol(path, options = {}, &block) perform_request Net::HTTP::Mkcol, path, options, &block end def lock(path, options = {}, &block) perform_request Net::HTTP::Lock, path, options, &block end def unlock(path, options = {}, &block) perform_request Net::HTTP::Unlock, path, options, &block end def build_request(http_method, path, options = {}) options = ModuleInheritableAttributes.hash_deep_dup(default_options).merge(options) HeadersProcessor.new(headers, options).call process_cookies(options) Request.new(http_method, path, options) end attr_reader :default_options private def validate_timeout_argument(timeout_type, value) raise ArgumentError, "#{ timeout_type } must be an integer or float" unless value && (value.is_a?(Integer) || value.is_a?(Float)) end def ensure_method_maintained_across_redirects(options) unless options.key?(:maintain_method_across_redirects) options[:maintain_method_across_redirects] = true end end def perform_request(http_method, path, options, &block) #:nodoc: build_request(http_method, path, options).perform(&block) end def process_cookies(options) #:nodoc: return unless options[:cookies] || default_cookies.any? options[:headers] ||= headers.dup options[:headers]['cookie'] = cookies.merge(options.delete(:cookies) || {}).to_cookie_string end def validate_format if format && parser.respond_to?(:supports_format?) && !parser.supports_format?(format) supported_format_names = parser.supported_formats.map(&:to_s).sort.join(', ') raise UnsupportedFormat, "'#{format.inspect}' Must be one of: #{supported_format_names}" end end end def self.normalize_base_uri(url) #:nodoc: normalized_url = url.dup use_ssl = (normalized_url =~ /^https/) || (normalized_url =~ /:443\b/) ends_with_slash = normalized_url =~ /\/$/ normalized_url.chop! if ends_with_slash normalized_url.gsub!(/^https?:\/\//i, '') "http#{'s' if use_ssl}://#{normalized_url}" end class Basement #:nodoc: include HTTParty end def self.get(*args, &block) Basement.get(*args, &block) end def self.post(*args, &block) Basement.post(*args, &block) end def self.patch(*args, &block) Basement.patch(*args, &block) end def self.put(*args, &block) Basement.put(*args, &block) end def self.delete(*args, &block) Basement.delete(*args, &block) end def self.move(*args, &block) Basement.move(*args, &block) end def self.copy(*args, &block) Basement.copy(*args, &block) end def self.head(*args, &block) Basement.head(*args, &block) end def self.options(*args, &block) Basement.options(*args, &block) end def self.build_request(*args, &block) Basement.build_request(*args, &block) end end require 'httparty/hash_conversions' require 'httparty/utils' require 'httparty/exceptions' require 'httparty/parser' require 'httparty/request' require 'httparty/response'
ruby
MIT
55ec76e8d1df7903eab3f7c2367991400d3cf65e
2026-01-04T15:41:22.900579Z
false