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 |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/abstract_unit.rb | provider/vendor/rails/activeresource/test/abstract_unit.rb | require 'rubygems'
require 'test/unit'
require 'active_support/test_case'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
$:.unshift "#{File.dirname(__FILE__)}/../../activesupport/lib"
require 'active_resource'
require 'active_resource/http_mock'
$:.unshift "#{File.dirname(__FILE__)}/../test"
require 'setter_trap'
ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/debug.log")
def uses_gem(gem_name, test_name, version = '> 0')
gem gem_name.to_s, version
require gem_name.to_s
yield
rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/base_test.rb | provider/vendor/rails/activeresource/test/base_test.rb | require 'abstract_unit'
require "fixtures/person"
require "fixtures/customer"
require "fixtures/street_address"
require "fixtures/beast"
require "fixtures/proxy"
class BaseTest < Test::Unit::TestCase
def setup
@matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
@david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
@greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person')
@addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address')
@default_request_headers = { 'Content-Type' => 'application/xml' }
@rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person")
@people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people')
@people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
@addresses = [{ :id => 1, :street => '12345 Street' }].to_xml(:root => 'addresses')
# - deep nested resource -
# - Luis (Customer)
# - JK (Customer::Friend)
# - Mateo (Customer::Friend::Brother)
# - Edith (Customer::Friend::Brother::Child)
# - Martha (Customer::Friend::Brother::Child)
# - Felipe (Customer::Friend::Brother)
# - Bryan (Customer::Friend::Brother::Child)
# - Luke (Customer::Friend::Brother::Child)
# - Eduardo (Customer::Friend)
# - Sebas (Customer::Friend::Brother)
# - Andres (Customer::Friend::Brother::Child)
# - Jorge (Customer::Friend::Brother::Child)
# - Elsa (Customer::Friend::Brother)
# - Natacha (Customer::Friend::Brother::Child)
# - Milena (Customer::Friend::Brother)
#
@luis = {:id => 1, :name => 'Luis',
:friends => [{:name => 'JK',
:brothers => [{:name => 'Mateo',
:children => [{:name => 'Edith'},{:name => 'Martha'}]},
{:name => 'Felipe',
:children => [{:name => 'Bryan'},{:name => 'Luke'}]}]},
{:name => 'Eduardo',
:brothers => [{:name => 'Sebas',
:children => [{:name => 'Andres'},{:name => 'Jorge'}]},
{:name => 'Elsa',
:children => [{:name => 'Natacha'}]},
{:name => 'Milena',
:children => []}]}]}.to_xml(:root => 'customer')
# - resource with yaml array of strings; for ActiveRecords using serialize :bar, Array
@marty = <<-eof.strip
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<person>
<id type=\"integer\">5</id>
<name>Marty</name>
<colors type=\"yaml\">---
- \"red\"
- \"green\"
- \"blue\"
</colors>
</person>
eof
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, @matz
mock.get "/people/2.xml", {}, @david
mock.get "/people/5.xml", {}, @marty
mock.get "/people/Greg.xml", {}, @greg
mock.get "/people/4.xml", {'key' => 'value'}, nil, 404
mock.put "/people/1.xml", {}, nil, 204
mock.delete "/people/1.xml", {}, nil, 200
mock.delete "/people/2.xml", {}, nil, 400
mock.get "/people/99.xml", {}, nil, 404
mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml'
mock.get "/people.xml", {}, @people
mock.get "/people/1/addresses.xml", {}, @addresses
mock.get "/people/1/addresses/1.xml", {}, @addy
mock.get "/people/1/addresses/2.xml", {}, nil, 404
mock.get "/people/2/addresses/1.xml", {}, nil, 404
mock.get "/people/Greg/addresses/1.xml", {}, @addy
mock.put "/people/1/addresses/1.xml", {}, nil, 204
mock.delete "/people/1/addresses/1.xml", {}, nil, 200
mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5'
mock.get "/people//addresses.xml", {}, nil, 404
mock.get "/people//addresses/1.xml", {}, nil, 404
mock.put "/people//addresses/1.xml", {}, nil, 404
mock.delete "/people//addresses/1.xml", {}, nil, 404
mock.post "/people//addresses.xml", {}, nil, 404
mock.head "/people/1.xml", {}, nil, 200
mock.head "/people/Greg.xml", {}, nil, 200
mock.head "/people/99.xml", {}, nil, 404
mock.head "/people/1/addresses/1.xml", {}, nil, 200
mock.head "/people/1/addresses/2.xml", {}, nil, 404
mock.head "/people/2/addresses/1.xml", {}, nil, 404
mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
# customer
mock.get "/customers/1.xml", {}, @luis
end
Person.user = nil
Person.password = nil
end
def test_site_accessor_accepts_uri_or_string_argument
site = URI.parse('http://localhost')
assert_nothing_raised { Person.site = 'http://localhost' }
assert_equal site, Person.site
assert_nothing_raised { Person.site = site }
assert_equal site, Person.site
end
def test_should_use_site_prefix_and_credentials
assert_equal 'http://foo:bar@beast.caboo.se', Forum.site.to_s
assert_equal 'http://foo:bar@beast.caboo.se/forums/:forum_id', Topic.site.to_s
end
def test_site_variable_can_be_reset
actor = Class.new(ActiveResource::Base)
assert_nil actor.site
actor.site = 'http://localhost:31337'
actor.site = nil
assert_nil actor.site
end
def test_proxy_accessor_accepts_uri_or_string_argument
proxy = URI.parse('http://localhost')
assert_nothing_raised { Person.proxy = 'http://localhost' }
assert_equal proxy, Person.proxy
assert_nothing_raised { Person.proxy = proxy }
assert_equal proxy, Person.proxy
end
def test_should_use_proxy_prefix_and_credentials
assert_equal 'http://user:password@proxy.local:3000', ProxyResource.proxy.to_s
end
def test_proxy_variable_can_be_reset
actor = Class.new(ActiveResource::Base)
assert_nil actor.site
actor.proxy = 'http://localhost:31337'
actor.proxy = nil
assert_nil actor.site
end
def test_should_accept_setting_user
Forum.user = 'david'
assert_equal('david', Forum.user)
assert_equal('david', Forum.connection.user)
end
def test_should_accept_setting_password
Forum.password = 'test123'
assert_equal('test123', Forum.password)
assert_equal('test123', Forum.connection.password)
end
def test_should_accept_setting_timeout
Forum.timeout = 5
assert_equal(5, Forum.timeout)
assert_equal(5, Forum.connection.timeout)
end
def test_should_accept_setting_ssl_options
expected = {:verify => 1}
Forum.ssl_options= expected
assert_equal(expected, Forum.ssl_options)
assert_equal(expected, Forum.connection.ssl_options)
end
def test_user_variable_can_be_reset
actor = Class.new(ActiveResource::Base)
actor.site = 'http://cinema'
assert_nil actor.user
actor.user = 'username'
actor.user = nil
assert_nil actor.user
assert_nil actor.connection.user
end
def test_password_variable_can_be_reset
actor = Class.new(ActiveResource::Base)
actor.site = 'http://cinema'
assert_nil actor.password
actor.password = 'username'
actor.password = nil
assert_nil actor.password
assert_nil actor.connection.password
end
def test_timeout_variable_can_be_reset
actor = Class.new(ActiveResource::Base)
actor.site = 'http://cinema'
assert_nil actor.timeout
actor.timeout = 5
actor.timeout = nil
assert_nil actor.timeout
assert_nil actor.connection.timeout
end
def test_ssl_options_hash_can_be_reset
actor = Class.new(ActiveResource::Base)
actor.site = 'https://cinema'
assert_nil actor.ssl_options
actor.ssl_options = {:foo => 5}
actor.ssl_options = nil
assert_nil actor.ssl_options
assert_nil actor.connection.ssl_options
end
def test_credentials_from_site_are_decoded
actor = Class.new(ActiveResource::Base)
actor.site = 'http://my%40email.com:%31%32%33@cinema'
assert_equal("my@email.com", actor.user)
assert_equal("123", actor.password)
end
def test_site_reader_uses_superclass_site_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.site
assert_nil Class.new(ActiveResource::Base).site
# Subclass uses superclass site.
actor = Class.new(Person)
assert_equal Person.site, actor.site
# Subclass returns frozen superclass copy.
assert !Person.site.frozen?
assert actor.site.frozen?
# Changing subclass site doesn't change superclass site.
actor.site = 'http://localhost:31337'
assert_not_equal Person.site, actor.site
# Changed subclass site is not frozen.
assert !actor.site.frozen?
# Changing superclass site doesn't overwrite subclass site.
Person.site = 'http://somewhere.else'
assert_not_equal Person.site, actor.site
# Changing superclass site after subclassing changes subclass site.
jester = Class.new(actor)
actor.site = 'http://nomad'
assert_equal actor.site, jester.site
assert jester.site.frozen?
# Subclasses are always equal to superclass site when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = 'http://market'
assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class'
fruit.site = 'http://supermarket'
assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class'
end
def test_proxy_reader_uses_superclass_site_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.proxy
assert_nil Class.new(ActiveResource::Base).proxy
# Subclass uses superclass proxy.
actor = Class.new(Person)
assert_equal Person.proxy, actor.proxy
# Subclass returns frozen superclass copy.
assert !Person.proxy.frozen?
assert actor.proxy.frozen?
# Changing subclass proxy doesn't change superclass site.
actor.proxy = 'http://localhost:31337'
assert_not_equal Person.proxy, actor.proxy
# Changed subclass proxy is not frozen.
assert !actor.proxy.frozen?
# Changing superclass proxy doesn't overwrite subclass site.
Person.proxy = 'http://somewhere.else'
assert_not_equal Person.proxy, actor.proxy
# Changing superclass proxy after subclassing changes subclass site.
jester = Class.new(actor)
actor.proxy = 'http://nomad'
assert_equal actor.proxy, jester.proxy
assert jester.proxy.frozen?
# Subclasses are always equal to superclass proxy when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.proxy = 'http://market'
assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class'
fruit.proxy = 'http://supermarket'
assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class'
end
def test_user_reader_uses_superclass_user_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.user
assert_nil Class.new(ActiveResource::Base).user
Person.user = 'anonymous'
# Subclass uses superclass user.
actor = Class.new(Person)
assert_equal Person.user, actor.user
# Subclass returns frozen superclass copy.
assert !Person.user.frozen?
assert actor.user.frozen?
# Changing subclass user doesn't change superclass user.
actor.user = 'david'
assert_not_equal Person.user, actor.user
# Changing superclass user doesn't overwrite subclass user.
Person.user = 'john'
assert_not_equal Person.user, actor.user
# Changing superclass user after subclassing changes subclass user.
jester = Class.new(actor)
actor.user = 'john.doe'
assert_equal actor.user, jester.user
# Subclasses are always equal to superclass user when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.user = 'manager'
assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class'
fruit.user = 'client'
assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class'
end
def test_password_reader_uses_superclass_password_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.password
assert_nil Class.new(ActiveResource::Base).password
Person.password = 'my-password'
# Subclass uses superclass password.
actor = Class.new(Person)
assert_equal Person.password, actor.password
# Subclass returns frozen superclass copy.
assert !Person.password.frozen?
assert actor.password.frozen?
# Changing subclass password doesn't change superclass password.
actor.password = 'secret'
assert_not_equal Person.password, actor.password
# Changing superclass password doesn't overwrite subclass password.
Person.password = 'super-secret'
assert_not_equal Person.password, actor.password
# Changing superclass password after subclassing changes subclass password.
jester = Class.new(actor)
actor.password = 'even-more-secret'
assert_equal actor.password, jester.password
# Subclasses are always equal to superclass password when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.password = 'mega-secret'
assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class'
fruit.password = 'ok-password'
assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class'
end
def test_timeout_reader_uses_superclass_timeout_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.timeout
assert_nil Class.new(ActiveResource::Base).timeout
Person.timeout = 5
# Subclass uses superclass timeout.
actor = Class.new(Person)
assert_equal Person.timeout, actor.timeout
# Changing subclass timeout doesn't change superclass timeout.
actor.timeout = 10
assert_not_equal Person.timeout, actor.timeout
# Changing superclass timeout doesn't overwrite subclass timeout.
Person.timeout = 15
assert_not_equal Person.timeout, actor.timeout
# Changing superclass timeout after subclassing changes subclass timeout.
jester = Class.new(actor)
actor.timeout = 20
assert_equal actor.timeout, jester.timeout
# Subclasses are always equal to superclass timeout when not overridden.
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.timeout = 25
assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class'
fruit.timeout = 30
assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class'
end
def test_ssl_options_reader_uses_superclass_ssl_options_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.ssl_options
assert_nil Class.new(ActiveResource::Base).ssl_options
Person.ssl_options = {:foo => 'bar'}
# Subclass uses superclass ssl_options.
actor = Class.new(Person)
assert_equal Person.ssl_options, actor.ssl_options
# Changing subclass ssl_options doesn't change superclass ssl_options.
actor.ssl_options = {:baz => ''}
assert_not_equal Person.ssl_options, actor.ssl_options
# Changing superclass ssl_options doesn't overwrite subclass ssl_options.
Person.ssl_options = {:color => 'blue'}
assert_not_equal Person.ssl_options, actor.ssl_options
# Changing superclass ssl_options after subclassing changes subclass ssl_options.
jester = Class.new(actor)
actor.ssl_options = {:color => 'red'}
assert_equal actor.ssl_options, jester.ssl_options
# Subclasses are always equal to superclass ssl_options when not overridden.
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.ssl_options = {:alpha => 'betas'}
assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class'
fruit.ssl_options = {:omega => 'moos'}
assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class'
end
def test_updating_baseclass_site_object_wipes_descendent_cached_connection_objects
# Subclasses are always equal to superclass site when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = 'http://market'
assert_equal fruit.connection.site, apple.connection.site
first_connection = apple.connection.object_id
fruit.site = 'http://supermarket'
assert_equal fruit.connection.site, apple.connection.site
second_connection = apple.connection.object_id
assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
end
def test_updating_baseclass_user_wipes_descendent_cached_connection_objects
# Subclasses are always equal to superclass user when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = 'http://market'
fruit.user = 'david'
assert_equal fruit.connection.user, apple.connection.user
first_connection = apple.connection.object_id
fruit.user = 'john'
assert_equal fruit.connection.user, apple.connection.user
second_connection = apple.connection.object_id
assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
end
def test_updating_baseclass_password_wipes_descendent_cached_connection_objects
# Subclasses are always equal to superclass password when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = 'http://market'
fruit.password = 'secret'
assert_equal fruit.connection.password, apple.connection.password
first_connection = apple.connection.object_id
fruit.password = 'supersecret'
assert_equal fruit.connection.password, apple.connection.password
second_connection = apple.connection.object_id
assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
end
def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects
# Subclasses are always equal to superclass timeout when not overridden
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = 'http://market'
fruit.timeout = 5
assert_equal fruit.connection.timeout, apple.connection.timeout
first_connection = apple.connection.object_id
fruit.timeout = 10
assert_equal fruit.connection.timeout, apple.connection.timeout
second_connection = apple.connection.object_id
assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
end
def test_collection_name
assert_equal "people", Person.collection_name
end
def test_collection_path
assert_equal '/people.xml', Person.collection_path
end
def test_collection_path_with_parameters
assert_equal '/people.xml?gender=male', Person.collection_path(:gender => 'male')
assert_equal '/people.xml?gender=false', Person.collection_path(:gender => false)
assert_equal '/people.xml?gender=', Person.collection_path(:gender => nil)
assert_equal '/people.xml?gender=male', Person.collection_path('gender' => 'male')
# Use includes? because ordering of param hash is not guaranteed
assert Person.collection_path(:gender => 'male', :student => true).include?('/people.xml?')
assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male')
assert Person.collection_path(:gender => 'male', :student => true).include?('student=true')
assert_equal '/people.xml?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
assert_equal '/people.xml?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'})
end
def test_custom_element_path
assert_equal '/people/1/addresses/1.xml', StreetAddress.element_path(1, :person_id => 1)
assert_equal '/people/1/addresses/1.xml', StreetAddress.element_path(1, 'person_id' => 1)
assert_equal '/people/Greg/addresses/1.xml', StreetAddress.element_path(1, 'person_id' => 'Greg')
end
def test_custom_element_path_with_redefined_to_param
Person.module_eval do
alias_method :original_to_param_element_path, :to_param
def to_param
name
end
end
# Class method.
assert_equal '/people/Greg.xml', Person.element_path('Greg')
# Protected Instance method.
assert_equal '/people/Greg.xml', Person.find('Greg').send(:element_path)
ensure
# revert back to original
Person.module_eval do
# save the 'new' to_param so we don't get a warning about discarding the method
alias_method :element_path_to_param, :to_param
alias_method :to_param, :original_to_param_element_path
end
end
def test_custom_element_path_with_parameters
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1)
assert_equal '/people/1/addresses/1.xml?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
end
def test_custom_element_path_with_prefix_and_parameters
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, {:person_id => 1}, {:type => 'work'})
end
def test_custom_collection_path
assert_equal '/people/1/addresses.xml', StreetAddress.collection_path(:person_id => 1)
assert_equal '/people/1/addresses.xml', StreetAddress.collection_path('person_id' => 1)
end
def test_custom_collection_path_with_parameters
assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path(:person_id => 1, :type => 'work')
assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path('person_id' => 1, :type => 'work')
end
def test_custom_collection_path_with_prefix_and_parameters
assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path({:person_id => 1}, {:type => 'work'})
end
def test_custom_element_name
assert_equal 'address', StreetAddress.element_name
end
def test_custom_collection_name
assert_equal 'addresses', StreetAddress.collection_name
end
def test_prefix
assert_equal "/", Person.prefix
assert_equal Set.new, Person.__send__(:prefix_parameters)
end
def test_set_prefix
SetterTrap.rollback_sets(Person) do |person_class|
person_class.prefix = "the_prefix"
assert_equal "the_prefix", person_class.prefix
end
end
def test_set_prefix_with_inline_keys
SetterTrap.rollback_sets(Person) do |person_class|
person_class.prefix = "the_prefix:the_param"
assert_equal "the_prefixthe_param_value", person_class.prefix(:the_param => "the_param_value")
end
end
def test_set_prefix_twice_should_clear_params
SetterTrap.rollback_sets(Person) do |person_class|
person_class.prefix = "the_prefix/:the_param1"
assert_equal Set.new([:the_param1]), person_class.prefix_parameters
person_class.prefix = "the_prefix/:the_param2"
assert_equal Set.new([:the_param2]), person_class.prefix_parameters
end
end
def test_set_prefix_with_default_value
SetterTrap.rollback_sets(Person) do |person_class|
person_class.set_prefix
assert_equal "/", person_class.prefix
end
end
def test_custom_prefix
assert_equal '/people//', StreetAddress.prefix
assert_equal '/people/1/', StreetAddress.prefix(:person_id => 1)
assert_equal [:person_id].to_set, StreetAddress.__send__(:prefix_parameters)
end
def test_find_by_id
matz = Person.find(1)
assert_kind_of Person, matz
assert_equal "Matz", matz.name
assert matz.name?
end
def test_respond_to
matz = Person.find(1)
assert matz.respond_to?(:name)
assert matz.respond_to?(:name=)
assert matz.respond_to?(:name?)
assert !matz.respond_to?(:super_scalable_stuff)
end
def test_find_by_id_with_custom_prefix
addy = StreetAddress.find(1, :params => { :person_id => 1 })
assert_kind_of StreetAddress, addy
assert_equal '12345 Street', addy.street
end
def test_find_all
all = Person.find(:all)
assert_equal 2, all.size
assert_kind_of Person, all.first
assert_equal "Matz", all.first.name
assert_equal "David", all.last.name
end
def test_find_first
matz = Person.find(:first)
assert_kind_of Person, matz
assert_equal "Matz", matz.name
end
def test_find_last
david = Person.find(:last)
assert_kind_of Person, david
assert_equal 'David', david.name
end
def test_custom_header
Person.headers['key'] = 'value'
assert_raise(ActiveResource::ResourceNotFound) { Person.find(4) }
ensure
Person.headers.delete('key')
end
def test_find_by_id_not_found
assert_raise(ActiveResource::ResourceNotFound) { Person.find(99) }
assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1) }
end
def test_find_all_by_from
ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.xml", {}, @people_david }
people = Person.find(:all, :from => "/companies/1/people.xml")
assert_equal 1, people.size
assert_equal "David", people.first.name
end
def test_find_all_by_from_with_options
ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.xml", {}, @people_david }
people = Person.find(:all, :from => "/companies/1/people.xml")
assert_equal 1, people.size
assert_equal "David", people.first.name
end
def test_find_all_by_symbol_from
ActiveResource::HttpMock.respond_to { |m| m.get "/people/managers.xml", {}, @people_david }
people = Person.find(:all, :from => :managers)
assert_equal 1, people.size
assert_equal "David", people.first.name
end
def test_find_single_by_from
ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/manager.xml", {}, @david }
david = Person.find(:one, :from => "/companies/1/manager.xml")
assert_equal "David", david.name
end
def test_find_single_by_symbol_from
ActiveResource::HttpMock.respond_to { |m| m.get "/people/leader.xml", {}, @david }
david = Person.find(:one, :from => :leader)
assert_equal "David", david.name
end
def test_save
rick = Person.new
assert_equal true, rick.save
assert_equal '5', rick.id
end
def test_id_from_response
p = Person.new
resp = {'Location' => '/foo/bar/1'}
assert_equal '1', p.__send__(:id_from_response, resp)
resp['Location'] << '.xml'
assert_equal '1', p.__send__(:id_from_response, resp)
end
def test_id_from_response_without_location
p = Person.new
resp = {}
assert_equal nil, p.__send__(:id_from_response, resp)
end
def test_create_with_custom_prefix
matzs_house = StreetAddress.new(:person_id => 1)
matzs_house.save
assert_equal '5', matzs_house.id
end
# Test that loading a resource preserves its prefix_options.
def test_load_preserves_prefix_options
address = StreetAddress.find(1, :params => { :person_id => 1 })
ryan = Person.new(:id => 1, :name => 'Ryan', :address => address)
assert_equal address.prefix_options, ryan.address.prefix_options
end
def test_reload_works_with_prefix_options
address = StreetAddress.find(1, :params => { :person_id => 1 })
assert_equal address, address.reload
end
def test_reload_with_redefined_to_param
Person.module_eval do
alias_method :original_to_param_reload, :to_param
def to_param
name
end
end
person = Person.find('Greg')
assert_equal person, person.reload
ensure
# revert back to original
Person.module_eval do
# save the 'new' to_param so we don't get a warning about discarding the method
alias_method :reload_to_param, :to_param
alias_method :to_param, :original_to_param_reload
end
end
def test_reload_works_without_prefix_options
person = Person.find(:first)
assert_equal person, person.reload
end
def test_create
rick = Person.create(:name => 'Rick')
assert rick.valid?
assert !rick.new?
assert_equal '5', rick.id
# test additional attribute returned on create
assert_equal 25, rick.age
# Test that save exceptions get bubbled up too
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/people.xml", {}, nil, 409
end
assert_raise(ActiveResource::ResourceConflict) { Person.create(:name => 'Rick') }
end
def test_create_without_location
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/people.xml", {}, nil, 201
end
person = Person.create(:name => 'Rick')
assert_equal nil, person.id
end
def test_clone
matz = Person.find(1)
matz_c = matz.clone
assert matz_c.new?
matz.attributes.each do |k, v|
assert_equal v, matz_c.send(k) if k != Person.primary_key
end
end
def test_nested_clone
addy = StreetAddress.find(1, :params => {:person_id => 1})
addy_c = addy.clone
assert addy_c.new?
addy.attributes.each do |k, v|
assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
end
assert_equal addy.prefix_options, addy_c.prefix_options
end
def test_complex_clone
matz = Person.find(1)
matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
matz.non_ar_hash = {:not => "an ARes instance"}
matz.non_ar_arr = ["not", "ARes"]
matz_c = matz.clone
assert matz_c.new?
assert_raise(NoMethodError) {matz_c.address}
assert_equal matz.non_ar_hash, matz_c.non_ar_hash
assert_equal matz.non_ar_arr, matz_c.non_ar_arr
# Test that actual copy, not just reference copy
matz.non_ar_hash[:not] = "changed"
assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
end
def test_update
matz = Person.find(:first)
matz.name = "David"
assert_kind_of Person, matz
assert_equal "David", matz.name
assert_equal true, matz.save
end
def test_update_with_custom_prefix_with_specific_id
addy = StreetAddress.find(1, :params => { :person_id => 1 })
addy.street = "54321 Street"
assert_kind_of StreetAddress, addy
assert_equal "54321 Street", addy.street
addy.save
end
def test_update_with_custom_prefix_without_specific_id
addy = StreetAddress.find(:first, :params => { :person_id => 1 })
addy.street = "54321 Lane"
assert_kind_of StreetAddress, addy
assert_equal "54321 Lane", addy.street
addy.save
end
def test_update_conflict
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/2.xml", {}, @david
mock.put "/people/2.xml", @default_request_headers, nil, 409
end
assert_raise(ActiveResource::ResourceConflict) { Person.find(2).save }
end
def test_destroy
assert Person.find(1).destroy
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, nil, 404
end
assert_raise(ActiveResource::ResourceNotFound) { Person.find(1).destroy }
end
def test_destroy_with_custom_prefix
assert StreetAddress.find(1, :params => { :person_id => 1 }).destroy
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1/addresses/1.xml", {}, nil, 404
end
assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) }
end
def test_destroy_with_410_gone
assert Person.find(1).destroy
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, nil, 410
end
assert_raise(ActiveResource::ResourceGone) { Person.find(1).destroy }
end
def test_delete
assert Person.delete(1)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/authorization_test.rb | provider/vendor/rails/activeresource/test/authorization_test.rb | require 'abstract_unit'
class AuthorizationTest < Test::Unit::TestCase
Response = Struct.new(:code)
def setup
@conn = ActiveResource::Connection.new('http://localhost')
@matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
@david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
@authenticated_conn = ActiveResource::Connection.new("http://david:test123@localhost")
@authorization_request_header = { 'Authorization' => 'Basic ZGF2aWQ6dGVzdDEyMw==' }
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/2.xml", @authorization_request_header, @david
mock.put "/people/2.xml", @authorization_request_header, nil, 204
mock.delete "/people/2.xml", @authorization_request_header, nil, 200
mock.post "/people/2/addresses.xml", @authorization_request_header, nil, 201, 'Location' => '/people/1/addresses/5'
end
end
def test_authorization_header
authorization_header = @authenticated_conn.__send__(:authorization_header)
assert_equal @authorization_request_header['Authorization'], authorization_header['Authorization']
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["david", "test123"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_with_username_but_no_password
@conn = ActiveResource::Connection.new("http://david:@localhost")
authorization_header = @conn.__send__(:authorization_header)
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["david"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_with_password_but_no_username
@conn = ActiveResource::Connection.new("http://:test123@localhost")
authorization_header = @conn.__send__(:authorization_header)
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["", "test123"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_with_decoded_credentials_from_url
@conn = ActiveResource::Connection.new("http://my%40email.com:%31%32%33@localhost")
authorization_header = @conn.__send__(:authorization_header)
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["my@email.com", "123"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_explicitly_setting_username_and_password
@authenticated_conn = ActiveResource::Connection.new("http://@localhost")
@authenticated_conn.user = 'david'
@authenticated_conn.password = 'test123'
authorization_header = @authenticated_conn.__send__(:authorization_header)
assert_equal @authorization_request_header['Authorization'], authorization_header['Authorization']
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["david", "test123"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_explicitly_setting_username_but_no_password
@conn = ActiveResource::Connection.new("http://@localhost")
@conn.user = "david"
authorization_header = @conn.__send__(:authorization_header)
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["david"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_authorization_header_explicitly_setting_password_but_no_username
@conn = ActiveResource::Connection.new("http://@localhost")
@conn.password = "test123"
authorization_header = @conn.__send__(:authorization_header)
authorization = authorization_header["Authorization"].to_s.split
assert_equal "Basic", authorization[0]
assert_equal ["", "test123"], ActiveSupport::Base64.decode64(authorization[1]).split(":")[0..1]
end
def test_get
david = @authenticated_conn.get("/people/2.xml")
assert_equal "David", david["name"]
end
def test_post
response = @authenticated_conn.post("/people/2/addresses.xml")
assert_equal "/people/1/addresses/5", response["Location"]
end
def test_put
response = @authenticated_conn.put("/people/2.xml")
assert_equal 204, response.code
end
def test_delete
response = @authenticated_conn.delete("/people/2.xml")
assert_equal 200, response.code
end
def test_raises_invalid_request_on_unauthorized_requests
assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2.xml") }
assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2/addresses.xml") }
assert_raise(ActiveResource::InvalidRequestError) { @conn.put("/people/2.xml") }
assert_raise(ActiveResource::InvalidRequestError) { @conn.delete("/people/2.xml") }
end
protected
def assert_response_raises(klass, code)
assert_raise(klass, "Expected response code #{code} to raise #{klass}") do
@conn.__send__(:handle_response, Response.new(code))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/base/equality_test.rb | provider/vendor/rails/activeresource/test/base/equality_test.rb | require 'abstract_unit'
require "fixtures/person"
require "fixtures/street_address"
class BaseEqualityTest < Test::Unit::TestCase
def setup
@new = Person.new
@one = Person.new(:id => 1)
@two = Person.new(:id => 2)
@street = StreetAddress.new(:id => 2)
end
def test_should_equal_self
assert @new == @new, '@new == @new'
assert @one == @one, '@one == @one'
end
def test_shouldnt_equal_new_resource
assert @new != @one, '@new != @one'
assert @one != @new, '@one != @new'
end
def test_shouldnt_equal_different_class
assert @two != @street, 'person != street_address with same id'
assert @street != @two, 'street_address != person with same id'
end
def test_eql_should_alias_equals_operator
assert_equal @new == @new, @new.eql?(@new)
assert_equal @new == @one, @new.eql?(@one)
assert_equal @one == @one, @one.eql?(@one)
assert_equal @one == @new, @one.eql?(@new)
assert_equal @one == @street, @one.eql?(@street)
end
def test_hash_should_be_id_hash
[@new, @one, @two, @street].each do |resource|
assert_equal resource.id.hash, resource.hash
end
end
def test_with_prefix_options
assert_equal @one == @one, @one.eql?(@one)
assert_equal @one == @one.dup, @one.eql?(@one.dup)
new_one = @one.dup
new_one.prefix_options = {:foo => 'bar'}
assert_not_equal @one, new_one
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/base/load_test.rb | provider/vendor/rails/activeresource/test/base/load_test.rb | require 'abstract_unit'
require "fixtures/person"
require "fixtures/street_address"
module Highrise
class Note < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
class Comment < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
module Deeply
module Nested
class Note < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
class Comment < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
module TestDifferentLevels
class Note < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
end
end
end
end
class BaseLoadTest < Test::Unit::TestCase
def setup
@matz = { :id => 1, :name => 'Matz' }
@first_address = { :id => 1, :street => '12345 Street' }
@addresses = [@first_address, { :id => 2, :street => '67890 Street' }]
@addresses_from_xml = { :street_addresses => @addresses }
@addresses_from_xml_single = { :street_addresses => [ @first_address ] }
@deep = { :id => 1, :street => {
:id => 1, :state => { :id => 1, :name => 'Oregon',
:notable_rivers => [
{ :id => 1, :name => 'Willamette' },
{ :id => 2, :name => 'Columbia', :rafted_by => @matz }],
:postal_codes => [ 97018, 1234567890 ],
:places => [ "Columbia City", "Unknown" ]}}}
@person = Person.new
end
def test_load_expects_hash
assert_raise(ArgumentError) { @person.load nil }
assert_raise(ArgumentError) { @person.load '<person id="1"/>' }
end
def test_load_simple_hash
assert_equal Hash.new, @person.attributes
assert_equal @matz.stringify_keys, @person.load(@matz).attributes
end
def test_load_one_with_existing_resource
address = @person.load(:street_address => @first_address).street_address
assert_kind_of StreetAddress, address
assert_equal @first_address.stringify_keys, address.attributes
end
def test_load_one_with_unknown_resource
address = silence_warnings { @person.load(:address => @first_address).address }
assert_kind_of Person::Address, address
assert_equal @first_address.stringify_keys, address.attributes
end
def test_load_collection_with_existing_resource
addresses = @person.load(@addresses_from_xml).street_addresses
assert_kind_of Array, addresses
addresses.each { |address| assert_kind_of StreetAddress, address }
assert_equal @addresses.map(&:stringify_keys), addresses.map(&:attributes)
end
def test_load_collection_with_unknown_resource
Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address)
assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated"
addresses = silence_warnings { @person.load(:addresses => @addresses).addresses }
assert Person.const_defined?(:Address), "Address should have been autocreated"
addresses.each { |address| assert_kind_of Person::Address, address }
assert_equal @addresses.map(&:stringify_keys), addresses.map(&:attributes)
end
def test_load_collection_with_single_existing_resource
addresses = @person.load(@addresses_from_xml_single).street_addresses
assert_kind_of Array, addresses
addresses.each { |address| assert_kind_of StreetAddress, address }
assert_equal [ @first_address ].map(&:stringify_keys), addresses.map(&:attributes)
end
def test_load_collection_with_single_unknown_resource
Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address)
assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated"
addresses = silence_warnings { @person.load(:addresses => [ @first_address ]).addresses }
assert Person.const_defined?(:Address), "Address should have been autocreated"
addresses.each { |address| assert_kind_of Person::Address, address }
assert_equal [ @first_address ].map(&:stringify_keys), addresses.map(&:attributes)
end
def test_recursively_loaded_collections
person = @person.load(@deep)
assert_equal @deep[:id], person.id
street = person.street
assert_kind_of Person::Street, street
assert_equal @deep[:street][:id], street.id
state = street.state
assert_kind_of Person::Street::State, state
assert_equal @deep[:street][:state][:id], state.id
rivers = state.notable_rivers
assert_kind_of Array, rivers
assert_kind_of Person::Street::State::NotableRiver, rivers.first
assert_equal @deep[:street][:state][:notable_rivers].first[:id], rivers.first.id
assert_equal @matz[:id], rivers.last.rafted_by.id
postal_codes = state.postal_codes
assert_kind_of Array, postal_codes
assert_equal 2, postal_codes.size
assert_kind_of Fixnum, postal_codes.first
assert_equal @deep[:street][:state][:postal_codes].first, postal_codes.first
assert_kind_of Numeric, postal_codes.last
assert_equal @deep[:street][:state][:postal_codes].last, postal_codes.last
places = state.places
assert_kind_of Array, places
assert_kind_of String, places.first
assert_equal @deep[:street][:state][:places].first, places.first
end
def test_nested_collections_within_the_same_namespace
n = Highrise::Note.new(:comments => [{ :name => "1" }])
assert_kind_of Highrise::Comment, n.comments.first
end
def test_nested_collections_within_deeply_nested_namespace
n = Highrise::Deeply::Nested::Note.new(:comments => [{ :name => "1" }])
assert_kind_of Highrise::Deeply::Nested::Comment, n.comments.first
end
def test_nested_collections_in_different_levels_of_namespaces
n = Highrise::Deeply::Nested::TestDifferentLevels::Note.new(:comments => [{ :name => "1" }])
assert_kind_of Highrise::Deeply::Nested::Comment, n.comments.first
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/base/custom_methods_test.rb | provider/vendor/rails/activeresource/test/base/custom_methods_test.rb | require 'abstract_unit'
require 'fixtures/person'
require 'fixtures/street_address'
class CustomMethodsTest < Test::Unit::TestCase
def setup
@matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
@matz_deep = { :id => 1, :name => 'Matz', :other => 'other' }.to_xml(:root => 'person')
@matz_array = [{ :id => 1, :name => 'Matz' }].to_xml(:root => 'people')
@ryan = { :name => 'Ryan' }.to_xml(:root => 'person')
@addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address')
@addy_deep = { :id => 1, :street => '12345 Street', :zip => "27519" }.to_xml(:root => 'address')
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, @matz
mock.get "/people/1/shallow.xml", {}, @matz
mock.get "/people/1/deep.xml", {}, @matz_deep
mock.get "/people/retrieve.xml?name=Matz", {}, @matz_array
mock.get "/people/managers.xml", {}, @matz_array
mock.post "/people/hire.xml?name=Matz", {}, nil, 201
mock.put "/people/1/promote.xml?position=Manager", {}, nil, 204
mock.put "/people/promote.xml?name=Matz", {}, nil, 204, {}
mock.put "/people/sort.xml?by=name", {}, nil, 204
mock.delete "/people/deactivate.xml?name=Matz", {}, nil, 200
mock.delete "/people/1/deactivate.xml", {}, nil, 200
mock.post "/people/new/register.xml", {}, @ryan, 201, 'Location' => '/people/5.xml'
mock.post "/people/1/register.xml", {}, @matz, 201
mock.get "/people/1/addresses/1.xml", {}, @addy
mock.get "/people/1/addresses/1/deep.xml", {}, @addy_deep
mock.put "/people/1/addresses/1/normalize_phone.xml?locale=US", {}, nil, 204
mock.put "/people/1/addresses/sort.xml?by=name", {}, nil, 204
mock.post "/people/1/addresses/new/link.xml", {}, { :street => '12345 Street' }.to_xml(:root => 'address'), 201, 'Location' => '/people/1/addresses/2.xml'
end
Person.user = nil
Person.password = nil
end
def teardown
ActiveResource::HttpMock.reset!
end
def test_custom_collection_method
# GET
assert_equal([{ "id" => 1, "name" => 'Matz' }], Person.get(:retrieve, :name => 'Matz'))
# POST
assert_equal(ActiveResource::Response.new("", 201, {}), Person.post(:hire, :name => 'Matz'))
# PUT
assert_equal ActiveResource::Response.new("", 204, {}),
Person.put(:promote, {:name => 'Matz'}, 'atestbody')
assert_equal ActiveResource::Response.new("", 204, {}), Person.put(:sort, :by => 'name')
# DELETE
Person.delete :deactivate, :name => 'Matz'
# Nested resource
assert_equal ActiveResource::Response.new("", 204, {}), StreetAddress.put(:sort, :person_id => 1, :by => 'name')
end
def test_custom_element_method
# Test GET against an element URL
assert_equal Person.find(1).get(:shallow), {"id" => 1, "name" => 'Matz'}
assert_equal Person.find(1).get(:deep), {"id" => 1, "name" => 'Matz', "other" => 'other'}
# Test PUT against an element URL
assert_equal ActiveResource::Response.new("", 204, {}), Person.find(1).put(:promote, {:position => 'Manager'}, 'body')
# Test DELETE against an element URL
assert_equal ActiveResource::Response.new("", 200, {}), Person.find(1).delete(:deactivate)
# With nested resources
assert_equal StreetAddress.find(1, :params => { :person_id => 1 }).get(:deep),
{ "id" => 1, "street" => '12345 Street', "zip" => "27519" }
assert_equal ActiveResource::Response.new("", 204, {}),
StreetAddress.find(1, :params => { :person_id => 1 }).put(:normalize_phone, :locale => 'US')
end
def test_custom_new_element_method
# Test POST against a new element URL
ryan = Person.new(:name => 'Ryan')
assert_equal ActiveResource::Response.new(@ryan, 201, {'Location' => '/people/5.xml'}), ryan.post(:register)
expected_request = ActiveResource::Request.new(:post, '/people/new/register.xml', @ryan)
assert_equal expected_request.body, ActiveResource::HttpMock.requests.first.body
# Test POST against a nested collection URL
addy = StreetAddress.new(:street => '123 Test Dr.', :person_id => 1)
assert_equal ActiveResource::Response.new({ :street => '12345 Street' }.to_xml(:root => 'address'),
201, {'Location' => '/people/1/addresses/2.xml'}),
addy.post(:link)
matz = Person.new(:id => 1, :name => 'Matz')
assert_equal ActiveResource::Response.new(@matz, 201), matz.post(:register)
end
def test_find_custom_resources
assert_equal 'Matz', Person.find(:all, :from => :managers).first.name
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/fixtures/street_address.rb | provider/vendor/rails/activeresource/test/fixtures/street_address.rb | class StreetAddress < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000/people/:person_id/"
self.element_name = 'address'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/fixtures/customer.rb | provider/vendor/rails/activeresource/test/fixtures/customer.rb | class Customer < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/fixtures/proxy.rb | provider/vendor/rails/activeresource/test/fixtures/proxy.rb | class ProxyResource < ActiveResource::Base
self.site = "http://localhost"
self.proxy = "http://user:password@proxy.local:3000"
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/fixtures/beast.rb | provider/vendor/rails/activeresource/test/fixtures/beast.rb | class BeastResource < ActiveResource::Base
self.site = 'http://beast.caboo.se'
site.user = 'foo'
site.password = 'bar'
end
class Forum < BeastResource
# taken from BeastResource
# self.site = 'http://beast.caboo.se'
end
class Topic < BeastResource
self.site += '/forums/:forum_id'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/test/fixtures/person.rb | provider/vendor/rails/activeresource/test/fixtures/person.rb | class Person < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource.rb | provider/vendor/rails/activeresource/lib/active_resource.rb | #--
# Copyright (c) 2006 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
begin
require 'active_support'
rescue LoadError
activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
if File.directory?(activesupport_path)
$:.unshift activesupport_path
require 'active_support'
end
end
require 'active_resource/formats'
require 'active_resource/base'
require 'active_resource/validations'
require 'active_resource/custom_methods'
module ActiveResource
Base.class_eval do
include Validations
include CustomMethods
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/activeresource.rb | provider/vendor/rails/activeresource/lib/activeresource.rb | require 'active_resource'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/version.rb | provider/vendor/rails/activeresource/lib/active_resource/version.rb | module ActiveResource
module VERSION #:nodoc:
MAJOR = 2
MINOR = 3
TINY = 4
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/exceptions.rb | provider/vendor/rails/activeresource/lib/active_resource/exceptions.rb | module ActiveResource
class ConnectionError < StandardError # :nodoc:
attr_reader :response
def initialize(response, message = nil)
@response = response
@message = message
end
def to_s
"Failed with #{response.code} #{response.message if response.respond_to?(:message)}"
end
end
# Raised when a Timeout::Error occurs.
class TimeoutError < ConnectionError
def initialize(message)
@message = message
end
def to_s; @message ;end
end
# Raised when a OpenSSL::SSL::SSLError occurs.
class SSLError < ConnectionError
def initialize(message)
@message = message
end
def to_s; @message ;end
end
# 3xx Redirection
class Redirection < ConnectionError # :nodoc:
def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end
end
# 4xx Client Error
class ClientError < ConnectionError; end # :nodoc:
# 400 Bad Request
class BadRequest < ClientError; end # :nodoc
# 401 Unauthorized
class UnauthorizedAccess < ClientError; end # :nodoc
# 403 Forbidden
class ForbiddenAccess < ClientError; end # :nodoc
# 404 Not Found
class ResourceNotFound < ClientError; end # :nodoc:
# 409 Conflict
class ResourceConflict < ClientError; end # :nodoc:
# 410 Gone
class ResourceGone < ClientError; end # :nodoc:
# 5xx Server Error
class ServerError < ConnectionError; end # :nodoc:
# 405 Method Not Allowed
class MethodNotAllowed < ClientError # :nodoc:
def allowed_methods
@response['Allow'].split(',').map { |verb| verb.strip.downcase.to_sym }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/custom_methods.rb | provider/vendor/rails/activeresource/lib/active_resource/custom_methods.rb | module ActiveResource
# A module to support custom REST methods and sub-resources, allowing you to break out
# of the "default" REST methods with your own custom resource requests. For example,
# say you use Rails to expose a REST service and configure your routes with:
#
# map.resources :people, :new => { :register => :post },
# :member => { :promote => :put, :deactivate => :delete }
# :collection => { :active => :get }
#
# This route set creates routes for the following HTTP requests:
#
# POST /people/new/register.xml # PeopleController.register
# PUT /people/1/promote.xml # PeopleController.promote with :id => 1
# DELETE /people/1/deactivate.xml # PeopleController.deactivate with :id => 1
# GET /people/active.xml # PeopleController.active
#
# Using this module, Active Resource can use these custom REST methods just like the
# standard methods.
#
# class Person < ActiveResource::Base
# self.site = "http://37s.sunrise.i:3000"
# end
#
# Person.new(:name => 'Ryan).post(:register) # POST /people/new/register.xml
# # => { :id => 1, :name => 'Ryan' }
#
# Person.find(1).put(:promote, :position => 'Manager') # PUT /people/1/promote.xml
# Person.find(1).delete(:deactivate) # DELETE /people/1/deactivate.xml
#
# Person.get(:active) # GET /people/active.xml
# # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}]
#
module CustomMethods
def self.included(base)
base.class_eval do
extend ActiveResource::CustomMethods::ClassMethods
include ActiveResource::CustomMethods::InstanceMethods
class << self
alias :orig_delete :delete
# Invokes a GET to a given custom REST method. For example:
#
# Person.get(:active) # GET /people/active.xml
# # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}]
#
# Person.get(:active, :awesome => true) # GET /people/active.xml?awesome=true
# # => [{:id => 1, :name => 'Ryan'}]
#
# Note: the objects returned from this method are not automatically converted
# into ActiveResource::Base instances - they are ordinary Hashes. If you are expecting
# ActiveResource::Base instances, use the <tt>find</tt> class method with the
# <tt>:from</tt> option. For example:
#
# Person.find(:all, :from => :active)
def get(custom_method_name, options = {})
connection.get(custom_method_collection_url(custom_method_name, options), headers)
end
def post(custom_method_name, options = {}, body = '')
connection.post(custom_method_collection_url(custom_method_name, options), body, headers)
end
def put(custom_method_name, options = {}, body = '')
connection.put(custom_method_collection_url(custom_method_name, options), body, headers)
end
def delete(custom_method_name, options = {})
# Need to jump through some hoops to retain the original class 'delete' method
if custom_method_name.is_a?(Symbol)
connection.delete(custom_method_collection_url(custom_method_name, options), headers)
else
orig_delete(custom_method_name, options)
end
end
end
end
end
module ClassMethods
def custom_method_collection_url(method_name, options = {})
prefix_options, query_options = split_options(options)
"#{prefix(prefix_options)}#{collection_name}/#{method_name}.#{format.extension}#{query_string(query_options)}"
end
end
module InstanceMethods
def get(method_name, options = {})
connection.get(custom_method_element_url(method_name, options), self.class.headers)
end
def post(method_name, options = {}, body = nil)
request_body = body.blank? ? encode : body
if new?
connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers)
else
connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers)
end
end
def put(method_name, options = {}, body = '')
connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
end
def delete(method_name, options = {})
connection.delete(custom_method_element_url(method_name, options), self.class.headers)
end
private
def custom_method_element_url(method_name, options = {})
"#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
end
def custom_method_new_element_url(method_name, options = {})
"#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/validations.rb | provider/vendor/rails/activeresource/lib/active_resource/validations.rb | module ActiveResource
class ResourceInvalid < ClientError #:nodoc:
end
# Active Resource validation is reported to and from this object, which is used by Base#save
# to determine whether the object in a valid state to be saved. See usage example in Validations.
class Errors
include Enumerable
attr_reader :errors
delegate :empty?, :to => :errors
def initialize(base) # :nodoc:
@base, @errors = base, {}
end
# Add an error to the base Active Resource object rather than an attribute.
#
# ==== Examples
# my_folder = Folder.find(1)
# my_folder.errors.add_to_base("You can't edit an existing folder")
# my_folder.errors.on_base
# # => "You can't edit an existing folder"
#
# my_folder.errors.add_to_base("This folder has been tagged as frozen")
# my_folder.valid?
# # => false
# my_folder.errors.on_base
# # => ["You can't edit an existing folder", "This folder has been tagged as frozen"]
#
def add_to_base(msg)
add(:base, msg)
end
# Adds an error to an Active Resource object's attribute (named for the +attribute+ parameter)
# with the error message in +msg+.
#
# ==== Examples
# my_resource = Node.find(1)
# my_resource.errors.add('name', 'can not be "base"') if my_resource.name == 'base'
# my_resource.errors.on('name')
# # => 'can not be "base"!'
#
# my_resource.errors.add('desc', 'can not be blank') if my_resource.desc == ''
# my_resource.valid?
# # => false
# my_resource.errors.on('desc')
# # => 'can not be blank!'
#
def add(attribute, msg)
@errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?
@errors[attribute.to_s] << msg
end
# Returns true if the specified +attribute+ has errors associated with it.
#
# ==== Examples
# my_resource = Disk.find(1)
# my_resource.errors.add('location', 'must be Main') unless my_resource.location == 'Main'
# my_resource.errors.on('location')
# # => 'must be Main!'
#
# my_resource.errors.invalid?('location')
# # => true
# my_resource.errors.invalid?('name')
# # => false
def invalid?(attribute)
!@errors[attribute.to_s].nil?
end
# A method to return the errors associated with +attribute+, which returns nil, if no errors are
# associated with the specified +attribute+, the error message if one error is associated with the specified +attribute+,
# or an array of error messages if more than one error is associated with the specified +attribute+.
#
# ==== Examples
# my_person = Person.new(params[:person])
# my_person.errors.on('login')
# # => nil
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.errors.on('login')
# # => 'can not be empty'
#
# my_person.errors.add('login', 'can not be longer than 10 characters') if my_person.login.length > 10
# my_person.errors.on('login')
# # => ['can not be empty', 'can not be longer than 10 characters']
def on(attribute)
errors = @errors[attribute.to_s]
return nil if errors.nil?
errors.size == 1 ? errors.first : errors
end
alias :[] :on
# A method to return errors assigned to +base+ object through add_to_base, which returns nil, if no errors are
# associated with the specified +attribute+, the error message if one error is associated with the specified +attribute+,
# or an array of error messages if more than one error is associated with the specified +attribute+.
#
# ==== Examples
# my_account = Account.find(1)
# my_account.errors.on_base
# # => nil
#
# my_account.errors.add_to_base("This account is frozen")
# my_account.errors.on_base
# # => "This account is frozen"
#
# my_account.errors.add_to_base("This account has been closed")
# my_account.errors.on_base
# # => ["This account is frozen", "This account has been closed"]
#
def on_base
on(:base)
end
# Yields each attribute and associated message per error added.
#
# ==== Examples
# my_person = Person.new(params[:person])
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.errors.add('password', 'can not be empty') if my_person.password == ''
# messages = ''
# my_person.errors.each {|attr, msg| messages += attr.humanize + " " + msg + "<br />"}
# messages
# # => "Login can not be empty<br />Password can not be empty<br />"
#
def each
@errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
end
# Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned
# through iteration as "First name can't be empty".
#
# ==== Examples
# my_person = Person.new(params[:person])
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.errors.add('password', 'can not be empty') if my_person.password == ''
# messages = ''
# my_person.errors.each_full {|msg| messages += msg + "<br/>"}
# messages
# # => "Login can not be empty<br />Password can not be empty<br />"
#
def each_full
full_messages.each { |msg| yield msg }
end
# Returns all the full error messages in an array.
#
# ==== Examples
# my_person = Person.new(params[:person])
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.errors.add('password', 'can not be empty') if my_person.password == ''
# messages = ''
# my_person.errors.full_messages.each {|msg| messages += msg + "<br/>"}
# messages
# # => "Login can not be empty<br />Password can not be empty<br />"
#
def full_messages
full_messages = []
@errors.each_key do |attr|
@errors[attr].each do |msg|
next if msg.nil?
if attr == "base"
full_messages << msg
else
full_messages << [attr.humanize, msg].join(' ')
end
end
end
full_messages
end
def clear
@errors = {}
end
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such
# with this as well.
#
# ==== Examples
# my_person = Person.new(params[:person])
# my_person.errors.size
# # => 0
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.errors.add('password', 'can not be empty') if my_person.password == ''
# my_person.error.size
# # => 2
#
def size
@errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
end
alias_method :count, :size
alias_method :length, :size
# Grabs errors from an array of messages (like ActiveRecord::Validations)
def from_array(messages)
clear
humanized_attributes = @base.attributes.keys.inject({}) { |h, attr_name| h.update(attr_name.humanize => attr_name) }
messages.each do |message|
attr_message = humanized_attributes.keys.detect do |attr_name|
if message[0, attr_name.size + 1] == "#{attr_name} "
add humanized_attributes[attr_name], message[(attr_name.size + 1)..-1]
end
end
add_to_base message if attr_message.nil?
end
end
# Grabs errors from the json response.
def from_json(json)
array = ActiveSupport::JSON.decode(json)['errors'] rescue []
from_array array
end
# Grabs errors from the XML response.
def from_xml(xml)
array = Array.wrap(Hash.from_xml(xml)['errors']['error']) rescue []
from_array array
end
end
# Module to support validation and errors with Active Resource objects. The module overrides
# Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned
# in the web service response. The module also adds an +errors+ collection that mimics the interface
# of the errors provided by ActiveRecord::Errors.
#
# ==== Example
#
# Consider a Person resource on the server requiring both a +first_name+ and a +last_name+ with a
# <tt>validates_presence_of :first_name, :last_name</tt> declaration in the model:
#
# person = Person.new(:first_name => "Jim", :last_name => "")
# person.save # => false (server returns an HTTP 422 status code and errors)
# person.valid? # => false
# person.errors.empty? # => false
# person.errors.count # => 1
# person.errors.full_messages # => ["Last name can't be empty"]
# person.errors.on(:last_name) # => "can't be empty"
# person.last_name = "Halpert"
# person.save # => true (and person is now saved to the remote service)
#
module Validations
def self.included(base) # :nodoc:
base.class_eval do
alias_method_chain :save, :validation
end
end
# Validate a resource and save (POST) it to the remote web service.
def save_with_validation
save_without_validation
true
rescue ResourceInvalid => error
case error.response['Content-Type']
when 'application/xml'
errors.from_xml(error.response.body)
when 'application/json'
errors.from_json(error.response.body)
end
false
end
# Checks for errors on an object (i.e., is resource.errors empty?).
#
# ==== Examples
# my_person = Person.create(params[:person])
# my_person.valid?
# # => true
#
# my_person.errors.add('login', 'can not be empty') if my_person.login == ''
# my_person.valid?
# # => false
def valid?
errors.empty?
end
# Returns the Errors object that holds all information about attribute error messages.
def errors
@errors ||= Errors.new(self)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/base.rb | provider/vendor/rails/activeresource/lib/active_resource/base.rb | require 'active_resource/connection'
require 'cgi'
require 'set'
module ActiveResource
# ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application.
#
# For an outline of what Active Resource is capable of, see link:files/vendor/rails/activeresource/README.html.
#
# == Automated mapping
#
# Active Resource objects represent your RESTful resources as manipulatable Ruby objects. To map resources
# to Ruby objects, Active Resource only needs a class name that corresponds to the resource name (e.g., the class
# Person maps to the resources people, very similarly to Active Record) and a +site+ value, which holds the
# URI of the resources.
#
# class Person < ActiveResource::Base
# self.site = "http://api.people.com:3000/"
# end
#
# Now the Person class is mapped to RESTful resources located at <tt>http://api.people.com:3000/people/</tt>, and
# you can now use Active Resource's lifecycles methods to manipulate resources. In the case where you already have
# an existing model with the same name as the desired RESTful resource you can set the +element_name+ value.
#
# class PersonResource < ActiveResource::Base
# self.site = "http://api.people.com:3000/"
# self.element_name = "person"
# end
#
#
# == Lifecycle methods
#
# Active Resource exposes methods for creating, finding, updating, and deleting resources
# from REST web services.
#
# ryan = Person.new(:first => 'Ryan', :last => 'Daigle')
# ryan.save # => true
# ryan.id # => 2
# Person.exists?(ryan.id) # => true
# ryan.exists? # => true
#
# ryan = Person.find(1)
# # Resource holding our newly created Person object
#
# ryan.first = 'Rizzle'
# ryan.save # => true
#
# ryan.destroy # => true
#
# As you can see, these are very similar to Active Record's lifecycle methods for database records.
# You can read more about each of these methods in their respective documentation.
#
# === Custom REST methods
#
# Since simple CRUD/lifecycle methods can't accomplish every task, Active Resource also supports
# defining your own custom REST methods. To invoke them, Active Resource provides the <tt>get</tt>,
# <tt>post</tt>, <tt>put</tt> and <tt>\delete</tt> methods where you can specify a custom REST method
# name to invoke.
#
# # POST to the custom 'register' REST method, i.e. POST /people/new/register.xml.
# Person.new(:name => 'Ryan').post(:register)
# # => { :id => 1, :name => 'Ryan', :position => 'Clerk' }
#
# # PUT an update by invoking the 'promote' REST method, i.e. PUT /people/1/promote.xml?position=Manager.
# Person.find(1).put(:promote, :position => 'Manager')
# # => { :id => 1, :name => 'Ryan', :position => 'Manager' }
#
# # GET all the positions available, i.e. GET /people/positions.xml.
# Person.get(:positions)
# # => [{:name => 'Manager'}, {:name => 'Clerk'}]
#
# # DELETE to 'fire' a person, i.e. DELETE /people/1/fire.xml.
# Person.find(1).delete(:fire)
#
# For more information on using custom REST methods, see the
# ActiveResource::CustomMethods documentation.
#
# == Validations
#
# You can validate resources client side by overriding validation methods in the base class.
#
# class Person < ActiveResource::Base
# self.site = "http://api.people.com:3000/"
# protected
# def validate
# errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/
# end
# end
#
# See the ActiveResource::Validations documentation for more information.
#
# == Authentication
#
# Many REST APIs will require authentication, usually in the form of basic
# HTTP authentication. Authentication can be specified by:
#
# === HTTP Basic Authentication
# * putting the credentials in the URL for the +site+ variable.
#
# class Person < ActiveResource::Base
# self.site = "http://ryan:password@api.people.com:3000/"
# end
#
# * defining +user+ and/or +password+ variables
#
# class Person < ActiveResource::Base
# self.site = "http://api.people.com:3000/"
# self.user = "ryan"
# self.password = "password"
# end
#
# For obvious security reasons, it is probably best if such services are available
# over HTTPS.
#
# Note: Some values cannot be provided in the URL passed to site. e.g. email addresses
# as usernames. In those situations you should use the separate user and password option.
#
# === Certificate Authentication
#
# * End point uses an X509 certificate for authentication. <tt>See ssl_options=</tt> for all options.
#
# class Person < ActiveResource::Base
# self.site = "https://secure.api.people.com/"
# self.ssl_options = {:cert => OpenSSL::X509::Certificate.new(File.open(pem_file))
# :key => OpenSSL::PKey::RSA.new(File.open(pem_file)),
# :ca_path => "/path/to/OpenSSL/formatted/CA_Certs",
# :verify_mode => OpenSSL::SSL::VERIFY_PEER}
# end
#
# == Errors & Validation
#
# Error handling and validation is handled in much the same manner as you're used to seeing in
# Active Record. Both the response code in the HTTP response and the body of the response are used to
# indicate that an error occurred.
#
# === Resource errors
#
# When a GET is requested for a resource that does not exist, the HTTP <tt>404</tt> (Resource Not Found)
# response code will be returned from the server which will raise an ActiveResource::ResourceNotFound
# exception.
#
# # GET http://api.people.com:3000/people/999.xml
# ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound
#
# <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The
# following HTTP response codes will also result in these exceptions:
#
# * 200..399 - Valid response, no exception (other than 301, 302)
# * 301, 302 - ActiveResource::Redirection
# * 400 - ActiveResource::BadRequest
# * 401 - ActiveResource::UnauthorizedAccess
# * 403 - ActiveResource::ForbiddenAccess
# * 404 - ActiveResource::ResourceNotFound
# * 405 - ActiveResource::MethodNotAllowed
# * 409 - ActiveResource::ResourceConflict
# * 410 - ActiveResource::ResourceGone
# * 422 - ActiveResource::ResourceInvalid (rescued by save as validation errors)
# * 401..499 - ActiveResource::ClientError
# * 500..599 - ActiveResource::ServerError
# * Other - ActiveResource::ConnectionError
#
# These custom exceptions allow you to deal with resource errors more naturally and with more precision
# rather than returning a general HTTP error. For example:
#
# begin
# ryan = Person.find(my_id)
# rescue ActiveResource::ResourceNotFound
# redirect_to :action => 'not_found'
# rescue ActiveResource::ResourceConflict, ActiveResource::ResourceInvalid
# redirect_to :action => 'new'
# end
#
# === Validation errors
#
# Active Resource supports validations on resources and will return errors if any these validations fail
# (e.g., "First name can not be blank" and so on). These types of errors are denoted in the response by
# a response code of <tt>422</tt> and an XML or JSON representation of the validation errors. The save operation will
# then fail (with a <tt>false</tt> return value) and the validation errors can be accessed on the resource in question.
#
# ryan = Person.find(1)
# ryan.first # => ''
# ryan.save # => false
#
# # When
# # PUT http://api.people.com:3000/people/1.xml
# # or
# # PUT http://api.people.com:3000/people/1.json
# # is requested with invalid values, the response is:
# #
# # Response (422):
# # <errors type="array"><error>First cannot be empty</error></errors>
# # or
# # {"errors":["First cannot be empty"]}
# #
#
# ryan.errors.invalid?(:first) # => true
# ryan.errors.full_messages # => ['First cannot be empty']
#
# Learn more about Active Resource's validation features in the ActiveResource::Validations documentation.
#
# === Timeouts
#
# Active Resource relies on HTTP to access RESTful APIs and as such is inherently susceptible to slow or
# unresponsive servers. In such cases, your Active Resource method calls could \timeout. You can control the
# amount of time before Active Resource times out with the +timeout+ variable.
#
# class Person < ActiveResource::Base
# self.site = "http://api.people.com:3000/"
# self.timeout = 5
# end
#
# This sets the +timeout+ to 5 seconds. You can adjust the +timeout+ to a value suitable for the RESTful API
# you are accessing. It is recommended to set this to a reasonably low value to allow your Active Resource
# clients (especially if you are using Active Resource in a Rails application) to fail-fast (see
# http://en.wikipedia.org/wiki/Fail-fast) rather than cause cascading failures that could incapacitate your
# server.
#
# When a \timeout occurs, an ActiveResource::TimeoutError is raised. You should rescue from
# ActiveResource::TimeoutError in your Active Resource method calls.
#
# Internally, Active Resource relies on Ruby's Net::HTTP library to make HTTP requests. Setting +timeout+
# sets the <tt>read_timeout</tt> of the internal Net::HTTP instance to the same value. The default
# <tt>read_timeout</tt> is 60 seconds on most Ruby implementations.
class Base
##
# :singleton-method:
# The logger for diagnosing and tracing Active Resource calls.
cattr_accessor :logger
class << self
# Gets the URI of the REST resources to map for this class. The site variable is required for
# Active Resource's mapping to work.
def site
# Not using superclass_delegating_reader because don't want subclasses to modify superclass instance
#
# With superclass_delegating_reader
#
# Parent.site = 'http://anonymous@test.com'
# Subclass.site # => 'http://anonymous@test.com'
# Subclass.site.user = 'david'
# Parent.site # => 'http://david@test.com'
#
# Without superclass_delegating_reader (expected behaviour)
#
# Parent.site = 'http://anonymous@test.com'
# Subclass.site # => 'http://anonymous@test.com'
# Subclass.site.user = 'david' # => TypeError: can't modify frozen object
#
if defined?(@site)
@site
elsif superclass != Object && superclass.site
superclass.site.dup.freeze
end
end
# Sets the URI of the REST resources to map for this class to the value in the +site+ argument.
# The site variable is required for Active Resource's mapping to work.
def site=(site)
@connection = nil
if site.nil?
@site = nil
else
@site = create_site_uri_from(site)
@user = URI.decode(@site.user) if @site.user
@password = URI.decode(@site.password) if @site.password
end
end
# Gets the \proxy variable if a proxy is required
def proxy
# Not using superclass_delegating_reader. See +site+ for explanation
if defined?(@proxy)
@proxy
elsif superclass != Object && superclass.proxy
superclass.proxy.dup.freeze
end
end
# Sets the URI of the http proxy to the value in the +proxy+ argument.
def proxy=(proxy)
@connection = nil
@proxy = proxy.nil? ? nil : create_proxy_uri_from(proxy)
end
# Gets the \user for REST HTTP authentication.
def user
# Not using superclass_delegating_reader. See +site+ for explanation
if defined?(@user)
@user
elsif superclass != Object && superclass.user
superclass.user.dup.freeze
end
end
# Sets the \user for REST HTTP authentication.
def user=(user)
@connection = nil
@user = user
end
# Gets the \password for REST HTTP authentication.
def password
# Not using superclass_delegating_reader. See +site+ for explanation
if defined?(@password)
@password
elsif superclass != Object && superclass.password
superclass.password.dup.freeze
end
end
# Sets the \password for REST HTTP authentication.
def password=(password)
@connection = nil
@password = password
end
# Sets the format that attributes are sent and received in from a mime type reference:
#
# Person.format = :json
# Person.find(1) # => GET /people/1.json
#
# Person.format = ActiveResource::Formats::XmlFormat
# Person.find(1) # => GET /people/1.xml
#
# Default format is <tt>:xml</tt>.
def format=(mime_type_reference_or_format)
format = mime_type_reference_or_format.is_a?(Symbol) ?
ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format
write_inheritable_attribute(:format, format)
connection.format = format if site
end
# Returns the current format, default is ActiveResource::Formats::XmlFormat.
def format
read_inheritable_attribute(:format) || ActiveResource::Formats[:xml]
end
# Sets the number of seconds after which requests to the REST API should time out.
def timeout=(timeout)
@connection = nil
@timeout = timeout
end
# Gets the number of seconds after which requests to the REST API should time out.
def timeout
if defined?(@timeout)
@timeout
elsif superclass != Object && superclass.timeout
superclass.timeout
end
end
# Options that will get applied to an SSL connection.
#
# * <tt>:key</tt> - An OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
# * <tt>:cert</tt> - An OpenSSL::X509::Certificate object as client certificate
# * <tt>:ca_file</tt> - Path to a CA certification file in PEM format. The file can contrain several CA certificates.
# * <tt>:ca_path</tt> - Path of a CA certification directory containing certifications in PEM format.
# * <tt>:verify_mode</tt> - Flags for server the certification verification at begining of SSL/TLS session. (OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable)
# * <tt>:verify_callback</tt> - The verify callback for the server certification verification.
# * <tt>:verify_depth</tt> - The maximum depth for the certificate chain verification.
# * <tt>:cert_store</tt> - OpenSSL::X509::Store to verify peer certificate.
# * <tt>:ssl_timeout</tt> -The SSL timeout in seconds.
def ssl_options=(opts={})
@connection = nil
@ssl_options = opts
end
# Returns the SSL options hash.
def ssl_options
if defined?(@ssl_options)
@ssl_options
elsif superclass != Object && superclass.ssl_options
superclass.ssl_options
end
end
# An instance of ActiveResource::Connection that is the base \connection to the remote service.
# The +refresh+ parameter toggles whether or not the \connection is refreshed at every request
# or not (defaults to <tt>false</tt>).
def connection(refresh = false)
if defined?(@connection) || superclass == Object
@connection = Connection.new(site, format) if refresh || @connection.nil?
@connection.proxy = proxy if proxy
@connection.user = user if user
@connection.password = password if password
@connection.timeout = timeout if timeout
@connection.ssl_options = ssl_options if ssl_options
@connection
else
superclass.connection
end
end
def headers
@headers ||= {}
end
# Do not include any modules in the default element name. This makes it easier to seclude ARes objects
# in a separate namespace without having to set element_name repeatedly.
attr_accessor_with_default(:element_name) { to_s.split("::").last.underscore } #:nodoc:
attr_accessor_with_default(:collection_name) { element_name.pluralize } #:nodoc:
attr_accessor_with_default(:primary_key, 'id') #:nodoc:
# Gets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>)
# This method is regenerated at runtime based on what the \prefix is set to.
def prefix(options={})
default = site.path
default << '/' unless default[-1..-1] == '/'
# generate the actual method based on the current site path
self.prefix = default
prefix(options)
end
# An attribute reader for the source string for the resource path \prefix. This
# method is regenerated at runtime based on what the \prefix is set to.
def prefix_source
prefix # generate #prefix and #prefix_source methods first
prefix_source
end
# Sets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>).
# Default value is <tt>site.path</tt>.
def prefix=(value = '/')
# Replace :placeholders with '#{embedded options[:lookups]}'
prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" }
# Clear prefix parameters in case they have been cached
@prefix_parameters = nil
# Redefine the new methods.
code = <<-end_code
def prefix_source() "#{value}" end
def prefix(options={}) "#{prefix_call}" end
end_code
silence_warnings { instance_eval code, __FILE__, __LINE__ }
rescue
logger.error "Couldn't set prefix: #{$!}\n #{code}"
raise
end
alias_method :set_prefix, :prefix= #:nodoc:
alias_method :set_element_name, :element_name= #:nodoc:
alias_method :set_collection_name, :collection_name= #:nodoc:
# Gets the element path for the given ID in +id+. If the +query_options+ parameter is omitted, Rails
# will split from the \prefix options.
#
# ==== Options
# +prefix_options+ - A \hash to add a \prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt>
# would yield a URL like <tt>/accounts/19/purchases.xml</tt>).
# +query_options+ - A \hash to add items to the query string for the request.
#
# ==== Examples
# Post.element_path(1)
# # => /posts/1.xml
#
# Comment.element_path(1, :post_id => 5)
# # => /posts/5/comments/1.xml
#
# Comment.element_path(1, :post_id => 5, :active => 1)
# # => /posts/5/comments/1.xml?active=1
#
# Comment.element_path(1, {:post_id => 5}, {:active => 1})
# # => /posts/5/comments/1.xml?active=1
#
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{id}.#{format.extension}#{query_string(query_options)}"
end
# Gets the collection path for the REST resources. If the +query_options+ parameter is omitted, Rails
# will split from the +prefix_options+.
#
# ==== Options
# * +prefix_options+ - A hash to add a prefix to the request for nested URL's (e.g., <tt>:account_id => 19</tt>
# would yield a URL like <tt>/accounts/19/purchases.xml</tt>).
# * +query_options+ - A hash to add items to the query string for the request.
#
# ==== Examples
# Post.collection_path
# # => /posts.xml
#
# Comment.collection_path(:post_id => 5)
# # => /posts/5/comments.xml
#
# Comment.collection_path(:post_id => 5, :active => 1)
# # => /posts/5/comments.xml?active=1
#
# Comment.collection_path({:post_id => 5}, {:active => 1})
# # => /posts/5/comments.xml?active=1
#
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
end
alias_method :set_primary_key, :primary_key= #:nodoc:
# Creates a new resource instance and makes a request to the remote service
# that it be saved, making it equivalent to the following simultaneous calls:
#
# ryan = Person.new(:first => 'ryan')
# ryan.save
#
# Returns the newly created resource. If a failure has occurred an
# exception will be raised (see <tt>save</tt>). If the resource is invalid and
# has not been saved then <tt>valid?</tt> will return <tt>false</tt>,
# while <tt>new?</tt> will still return <tt>true</tt>.
#
# ==== Examples
# Person.create(:name => 'Jeremy', :email => 'myname@nospam.com', :enabled => true)
# my_person = Person.find(:first)
# my_person.email # => myname@nospam.com
#
# dhh = Person.create(:name => 'David', :email => 'dhh@nospam.com', :enabled => true)
# dhh.valid? # => true
# dhh.new? # => false
#
# # We'll assume that there's a validation that requires the name attribute
# that_guy = Person.create(:name => '', :email => 'thatguy@nospam.com', :enabled => true)
# that_guy.valid? # => false
# that_guy.new? # => true
def create(attributes = {})
self.new(attributes).tap { |resource| resource.save }
end
# Core method for finding resources. Used similarly to Active Record's +find+ method.
#
# ==== Arguments
# The first argument is considered to be the scope of the query. That is, how many
# resources are returned from the request. It can be one of the following.
#
# * <tt>:one</tt> - Returns a single resource.
# * <tt>:first</tt> - Returns the first resource found.
# * <tt>:last</tt> - Returns the last resource found.
# * <tt>:all</tt> - Returns every resource that matches the request.
#
# ==== Options
#
# * <tt>:from</tt> - Sets the path or custom method that resources will be fetched from.
# * <tt>:params</tt> - Sets query and \prefix (nested URL) parameters.
#
# ==== Examples
# Person.find(1)
# # => GET /people/1.xml
#
# Person.find(:all)
# # => GET /people.xml
#
# Person.find(:all, :params => { :title => "CEO" })
# # => GET /people.xml?title=CEO
#
# Person.find(:first, :from => :managers)
# # => GET /people/managers.xml
#
# Person.find(:last, :from => :managers)
# # => GET /people/managers.xml
#
# Person.find(:all, :from => "/companies/1/people.xml")
# # => GET /companies/1/people.xml
#
# Person.find(:one, :from => :leader)
# # => GET /people/leader.xml
#
# Person.find(:all, :from => :developers, :params => { :language => 'ruby' })
# # => GET /people/developers.xml?language=ruby
#
# Person.find(:one, :from => "/companies/1/manager.xml")
# # => GET /companies/1/manager.xml
#
# StreetAddress.find(1, :params => { :person_id => 1 })
# # => GET /people/1/street_addresses/1.xml
def find(*arguments)
scope = arguments.slice!(0)
options = arguments.slice!(0) || {}
case scope
when :all then find_every(options)
when :first then find_every(options).first
when :last then find_every(options).last
when :one then find_one(options)
else find_single(scope, options)
end
end
# Deletes the resources with the ID in the +id+ parameter.
#
# ==== Options
# All options specify \prefix and query parameters.
#
# ==== Examples
# Event.delete(2) # sends DELETE /events/2
#
# Event.create(:name => 'Free Concert', :location => 'Community Center')
# my_event = Event.find(:first) # let's assume this is event with ID 7
# Event.delete(my_event.id) # sends DELETE /events/7
#
# # Let's assume a request to events/5/cancel.xml
# Event.delete(params[:id]) # sends DELETE /events/5
def delete(id, options = {})
connection.delete(element_path(id, options))
end
# Asserts the existence of a resource, returning <tt>true</tt> if the resource is found.
#
# ==== Examples
# Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
# Note.exists?(1) # => true
#
# Note.exists(1349) # => false
def exists?(id, options = {})
if id
prefix_options, query_options = split_options(options[:params])
path = element_path(id, prefix_options, query_options)
response = connection.head(path, headers)
response.code.to_i == 200
end
# id && !find_single(id, options).nil?
rescue ActiveResource::ResourceNotFound, ActiveResource::ResourceGone
false
end
private
# Find every resource
def find_every(options)
case from = options[:from]
when Symbol
instantiate_collection(get(from, options[:params]))
when String
path = "#{from}#{query_string(options[:params])}"
instantiate_collection(connection.get(path, headers) || [])
else
prefix_options, query_options = split_options(options[:params])
path = collection_path(prefix_options, query_options)
instantiate_collection( (connection.get(path, headers) || []), prefix_options )
end
end
# Find a single resource from a one-off URL
def find_one(options)
case from = options[:from]
when Symbol
instantiate_record(get(from, options[:params]))
when String
path = "#{from}#{query_string(options[:params])}"
instantiate_record(connection.get(path, headers))
end
end
# Find a single resource from the default URL
def find_single(scope, options)
prefix_options, query_options = split_options(options[:params])
path = element_path(scope, prefix_options, query_options)
instantiate_record(connection.get(path, headers), prefix_options)
end
def instantiate_collection(collection, prefix_options = {})
collection.collect! { |record| instantiate_record(record, prefix_options) }
end
def instantiate_record(record, prefix_options = {})
new(record).tap do |resource|
resource.prefix_options = prefix_options
end
end
# Accepts a URI and creates the site URI from that.
def create_site_uri_from(site)
site.is_a?(URI) ? site.dup : URI.parse(site)
end
# Accepts a URI and creates the proxy URI from that.
def create_proxy_uri_from(proxy)
proxy.is_a?(URI) ? proxy.dup : URI.parse(proxy)
end
# contains a set of the current prefix parameters.
def prefix_parameters
@prefix_parameters ||= prefix_source.scan(/:\w+/).map { |key| key[1..-1].to_sym }.to_set
end
# Builds the query string for the request.
def query_string(options)
"?#{options.to_query}" unless options.nil? || options.empty?
end
# split an option hash into two hashes, one containing the prefix options,
# and the other containing the leftovers.
def split_options(options = {})
prefix_options, query_options = {}, {}
(options || {}).each do |key, value|
next if key.blank?
(prefix_parameters.include?(key.to_sym) ? prefix_options : query_options)[key.to_sym] = value
end
[ prefix_options, query_options ]
end
end
attr_accessor :attributes #:nodoc:
attr_accessor :prefix_options #:nodoc:
# Constructor method for \new resources; the optional +attributes+ parameter takes a \hash
# of attributes for the \new resource.
#
# ==== Examples
# my_course = Course.new
# my_course.name = "Western Civilization"
# my_course.lecturer = "Don Trotter"
# my_course.save
#
# my_other_course = Course.new(:name => "Philosophy: Reason and Being", :lecturer => "Ralph Cling")
# my_other_course.save
def initialize(attributes = {})
@attributes = {}
@prefix_options = {}
load(attributes)
end
# Returns a \clone of the resource that hasn't been assigned an +id+ yet and
# is treated as a \new resource.
#
# ryan = Person.find(1)
# not_ryan = ryan.clone
# not_ryan.new? # => true
#
# Any active resource member attributes will NOT be cloned, though all other
# attributes are. This is to prevent the conflict between any +prefix_options+
# that refer to the original parent resource and the newly cloned parent
# resource that does not exist.
#
# ryan = Person.find(1)
# ryan.address = StreetAddress.find(1, :person_id => ryan.id)
# ryan.hash = {:not => "an ARes instance"}
#
# not_ryan = ryan.clone
# not_ryan.new? # => true
# not_ryan.address # => NoMethodError
# not_ryan.hash # => {:not => "an ARes instance"}
def clone
# Clone all attributes except the pk and any nested ARes
cloned = attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.inject({}) do |attrs, (k, v)|
attrs[k] = v.clone
attrs
end
# Form the new resource - bypass initialize of resource with 'new' as that will call 'load' which
# attempts to convert hashes into member objects and arrays into collections of objects. We want
# the raw objects to be cloned so we bypass load by directly setting the attributes hash.
resource = self.class.new({})
resource.prefix_options = self.prefix_options
resource.send :instance_variable_set, '@attributes', cloned
resource
end
# A method to determine if the resource a \new object (i.e., it has not been POSTed to the remote service yet).
#
# ==== Examples
# not_new = Computer.create(:brand => 'Apple', :make => 'MacBook', :vendor => 'MacMall')
# not_new.new? # => false
#
# is_new = Computer.new(:brand => 'IBM', :make => 'Thinkpad', :vendor => 'IBM')
# is_new.new? # => true
#
# is_new.save
# is_new.new? # => false
#
def new?
id.nil?
end
alias :new_record? :new?
# Gets the <tt>\id</tt> attribute of the resource.
def id
attributes[self.class.primary_key]
end
# Sets the <tt>\id</tt> attribute of the resource.
def id=(id)
attributes[self.class.primary_key] = id
end
# Allows Active Resource objects to be used as parameters in Action Pack URL generation.
def to_param
id && id.to_s
end
# Test for equality. Resource are equal if and only if +other+ is the same object or
# is an instance of the same class, is not <tt>new?</tt>, and has the same +id+.
#
# ==== Examples
# ryan = Person.create(:name => 'Ryan')
# jamie = Person.create(:name => 'Jamie')
#
# ryan == jamie
# # => false (Different name attribute and id)
#
# ryan_again = Person.new(:name => 'Ryan')
# ryan == ryan_again
# # => false (ryan_again is new?)
#
# ryans_clone = Person.create(:name => 'Ryan')
# ryan == ryans_clone
# # => false (Different id attributes)
#
# ryans_twin = Person.find(ryan.id)
# ryan == ryans_twin
# # => true
#
def ==(other)
other.equal?(self) || (other.instance_of?(self.class) && other.id == id && other.prefix_options == prefix_options)
end
# Tests for equality (delegates to ==).
def eql?(other)
self == other
end
# Delegates to id in order to allow two resources of the same type and \id to work with something like:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/http_mock.rb | provider/vendor/rails/activeresource/lib/active_resource/http_mock.rb | require 'active_resource/connection'
module ActiveResource
class InvalidRequestError < StandardError; end #:nodoc:
# One thing that has always been a pain with remote web services is testing. The HttpMock
# class makes it easy to test your Active Resource models by creating a set of mock responses to specific
# requests.
#
# To test your Active Resource model, you simply call the ActiveResource::HttpMock.respond_to
# method with an attached block. The block declares a set of URIs with expected input, and the output
# each request should return. The passed in block has any number of entries in the following generalized
# format:
#
# mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {})
#
# * <tt>http_method</tt> - The HTTP method to listen for. This can be +get+, +post+, +put+, +delete+ or
# +head+.
# * <tt>path</tt> - A string, starting with a "/", defining the URI that is expected to be
# called.
# * <tt>request_headers</tt> - Headers that are expected along with the request. This argument uses a
# hash format, such as <tt>{ "Content-Type" => "application/xml" }</tt>. This mock will only trigger
# if your tests sends a request with identical headers.
# * <tt>body</tt> - The data to be returned. This should be a string of Active Resource parseable content,
# such as XML.
# * <tt>status</tt> - The HTTP response code, as an integer, to return with the response.
# * <tt>response_headers</tt> - Headers to be returned with the response. Uses the same hash format as
# <tt>request_headers</tt> listed above.
#
# In order for a mock to deliver its content, the incoming request must match by the <tt>http_method</tt>,
# +path+ and <tt>request_headers</tt>. If no match is found an InvalidRequestError exception
# will be raised letting you know you need to create a new mock for that request.
#
# ==== Example
# def setup
# @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
# ActiveResource::HttpMock.respond_to do |mock|
# mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml"
# mock.get "/people/1.xml", {}, @matz
# mock.put "/people/1.xml", {}, nil, 204
# mock.delete "/people/1.xml", {}, nil, 200
# end
# end
#
# def test_get_matz
# person = Person.find(1)
# assert_equal "Matz", person.name
# end
#
class HttpMock
class Responder #:nodoc:
def initialize(responses)
@responses = responses
end
for method in [ :post, :put, :get, :delete, :head ]
# def post(path, request_headers = {}, body = nil, status = 200, response_headers = {})
# @responses[Request.new(:post, path, nil, request_headers)] = Response.new(body || "", status, response_headers)
# end
module_eval <<-EOE, __FILE__, __LINE__
def #{method}(path, request_headers = {}, body = nil, status = 200, response_headers = {})
@responses << [Request.new(:#{method}, path, nil, request_headers), Response.new(body || "", status, response_headers)]
end
EOE
end
end
class << self
# Returns an array of all request objects that have been sent to the mock. You can use this to check
# if your model actually sent an HTTP request.
#
# ==== Example
# def setup
# @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
# ActiveResource::HttpMock.respond_to do |mock|
# mock.get "/people/1.xml", {}, @matz
# end
# end
#
# def test_should_request_remote_service
# person = Person.find(1) # Call the remote service
#
# # This request object has the same HTTP method and path as declared by the mock
# expected_request = ActiveResource::Request.new(:get, "/people/1.xml")
#
# # Assert that the mock received, and responded to, the expected request from the model
# assert ActiveResource::HttpMock.requests.include?(expected_request)
# end
def requests
@@requests ||= []
end
# Returns the list of requests and their mocked responses. Look up a
# response for a request using responses.assoc(request).
def responses
@@responses ||= []
end
# Accepts a block which declares a set of requests and responses for the HttpMock to respond to. See the main
# ActiveResource::HttpMock description for a more detailed explanation.
def respond_to(pairs = {}) #:yields: mock
reset!
responses.concat pairs.to_a
if block_given?
yield Responder.new(responses)
else
Responder.new(responses)
end
end
# Deletes all logged requests and responses.
def reset!
requests.clear
responses.clear
end
end
# body? methods
{ true => %w(post put),
false => %w(get delete head) }.each do |has_body, methods|
methods.each do |method|
# def post(path, body, headers)
# request = ActiveResource::Request.new(:post, path, body, headers)
# self.class.requests << request
# self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for #{request}"))
# end
module_eval <<-EOE, __FILE__, __LINE__
def #{method}(path, #{'body, ' if has_body}headers)
request = ActiveResource::Request.new(:#{method}, path, #{has_body ? 'body, ' : 'nil, '}headers)
self.class.requests << request
self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for \#{request}"))
end
EOE
end
end
def initialize(site) #:nodoc:
@site = site
end
end
class Request
attr_accessor :path, :method, :body, :headers
def initialize(method, path, body = nil, headers = {})
@method, @path, @body, @headers = method, path, body, headers.merge(ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] => 'application/xml')
end
def ==(req)
path == req.path && method == req.method && headers == req.headers
end
def to_s
"<#{method.to_s.upcase}: #{path} [#{headers}] (#{body})>"
end
end
class Response
attr_accessor :body, :message, :code, :headers
def initialize(body, message = 200, headers = {})
@body, @message, @headers = body, message.to_s, headers
@code = @message[0,3].to_i
resp_cls = Net::HTTPResponse::CODE_TO_OBJ[@code.to_s]
if resp_cls && !resp_cls.body_permitted?
@body = nil
end
if @body.nil?
self['Content-Length'] = "0"
else
self['Content-Length'] = body.size.to_s
end
end
def success?
(200..299).include?(code)
end
def [](key)
headers[key]
end
def []=(key, value)
headers[key] = value
end
def ==(other)
if (other.is_a?(Response))
other.body == body && other.message == message && other.headers == headers
else
false
end
end
end
class Connection
private
silence_warnings do
def http
@http ||= HttpMock.new(@site)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/connection.rb | provider/vendor/rails/activeresource/lib/active_resource/connection.rb | require 'net/https'
require 'date'
require 'time'
require 'uri'
require 'benchmark'
module ActiveResource
class ConnectionError < StandardError # :nodoc:
attr_reader :response
def initialize(response, message = nil)
@response = response
@message = message
end
def to_s
"Failed with #{response.code} #{response.message if response.respond_to?(:message)}"
end
end
# Raised when a Timeout::Error occurs.
class TimeoutError < ConnectionError
def initialize(message)
@message = message
end
def to_s; @message ;end
end
# Raised when a OpenSSL::SSL::SSLError occurs.
class SSLError < ConnectionError
def initialize(message)
@message = message
end
def to_s; @message ;end
end
# 3xx Redirection
class Redirection < ConnectionError # :nodoc:
def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end
end
# 4xx Client Error
class ClientError < ConnectionError; end # :nodoc:
# 400 Bad Request
class BadRequest < ClientError; end # :nodoc
# 401 Unauthorized
class UnauthorizedAccess < ClientError; end # :nodoc
# 403 Forbidden
class ForbiddenAccess < ClientError; end # :nodoc
# 404 Not Found
class ResourceNotFound < ClientError; end # :nodoc:
# 409 Conflict
class ResourceConflict < ClientError; end # :nodoc:
# 410 Gone
class ResourceGone < ClientError; end # :nodoc:
# 5xx Server Error
class ServerError < ConnectionError; end # :nodoc:
# 405 Method Not Allowed
class MethodNotAllowed < ClientError # :nodoc:
def allowed_methods
@response['Allow'].split(',').map { |verb| verb.strip.downcase.to_sym }
end
end
# Class to handle connections to remote web services.
# This class is used by ActiveResource::Base to interface with REST
# services.
class Connection
HTTP_FORMAT_HEADER_NAMES = { :get => 'Accept',
:put => 'Content-Type',
:post => 'Content-Type',
:delete => 'Accept',
:head => 'Accept'
}
attr_reader :site, :user, :password, :timeout, :proxy, :ssl_options
attr_accessor :format
class << self
def requests
@@requests ||= []
end
end
# The +site+ parameter is required and will set the +site+
# attribute to the URI for the remote resource service.
def initialize(site, format = ActiveResource::Formats[:xml])
raise ArgumentError, 'Missing site URI' unless site
@user = @password = nil
self.site = site
self.format = format
end
# Set URI for remote service.
def site=(site)
@site = site.is_a?(URI) ? site : URI.parse(site)
@user = URI.decode(@site.user) if @site.user
@password = URI.decode(@site.password) if @site.password
end
# Set the proxy for remote service.
def proxy=(proxy)
@proxy = proxy.is_a?(URI) ? proxy : URI.parse(proxy)
end
# Set the user for remote service.
def user=(user)
@user = user
end
# Set password for remote service.
def password=(password)
@password = password
end
# Set the number of seconds after which HTTP requests to the remote service should time out.
def timeout=(timeout)
@timeout = timeout
end
# Hash of options applied to Net::HTTP instance when +site+ protocol is 'https'.
def ssl_options=(opts={})
@ssl_options = opts
end
# Execute a GET request.
# Used to get (find) resources.
def get(path, headers = {})
format.decode(request(:get, path, build_request_headers(headers, :get)).body)
end
# Execute a DELETE request (see HTTP protocol documentation if unfamiliar).
# Used to delete resources.
def delete(path, headers = {})
request(:delete, path, build_request_headers(headers, :delete))
end
# Execute a PUT request (see HTTP protocol documentation if unfamiliar).
# Used to update resources.
def put(path, body = '', headers = {})
request(:put, path, body.to_s, build_request_headers(headers, :put))
end
# Execute a POST request.
# Used to create new resources.
def post(path, body = '', headers = {})
request(:post, path, body.to_s, build_request_headers(headers, :post))
end
# Execute a HEAD request.
# Used to obtain meta-information about resources, such as whether they exist and their size (via response headers).
def head(path, headers = {})
request(:head, path, build_request_headers(headers, :head))
end
private
# Makes request to remote service.
def request(method, path, *arguments)
logger.info "#{method.to_s.upcase} #{site.scheme}://#{site.host}:#{site.port}#{path}" if logger
result = nil
ms = Benchmark.ms { result = http.send(method, path, *arguments) }
logger.info "--> %d %s (%d %.0fms)" % [result.code, result.message, result.body ? result.body.length : 0, ms] if logger
handle_response(result)
rescue Timeout::Error => e
raise TimeoutError.new(e.message)
rescue OpenSSL::SSL::SSLError => e
raise SSLError.new(e.message)
end
# Handles response and error codes from remote service.
def handle_response(response)
case response.code.to_i
when 301,302
raise(Redirection.new(response))
when 200...400
response
when 400
raise(BadRequest.new(response))
when 401
raise(UnauthorizedAccess.new(response))
when 403
raise(ForbiddenAccess.new(response))
when 404
raise(ResourceNotFound.new(response))
when 405
raise(MethodNotAllowed.new(response))
when 409
raise(ResourceConflict.new(response))
when 410
raise(ResourceGone.new(response))
when 422
raise(ResourceInvalid.new(response))
when 401...500
raise(ClientError.new(response))
when 500...600
raise(ServerError.new(response))
else
raise(ConnectionError.new(response, "Unknown response code: #{response.code}"))
end
end
# Creates new Net::HTTP instance for communication with
# remote service and resources.
def http
configure_http(new_http)
end
def new_http
if @proxy
Net::HTTP.new(@site.host, @site.port, @proxy.host, @proxy.port, @proxy.user, @proxy.password)
else
Net::HTTP.new(@site.host, @site.port)
end
end
def configure_http(http)
http = apply_ssl_options(http)
# Net::HTTP timeouts default to 60 seconds.
if @timeout
http.open_timeout = @timeout
http.read_timeout = @timeout
end
http
end
def apply_ssl_options(http)
return http unless @site.is_a?(URI::HTTPS)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
return http unless defined?(@ssl_options)
http.ca_path = @ssl_options[:ca_path] if @ssl_options[:ca_path]
http.ca_file = @ssl_options[:ca_file] if @ssl_options[:ca_file]
http.cert = @ssl_options[:cert] if @ssl_options[:cert]
http.key = @ssl_options[:key] if @ssl_options[:key]
http.cert_store = @ssl_options[:cert_store] if @ssl_options[:cert_store]
http.ssl_timeout = @ssl_options[:ssl_timeout] if @ssl_options[:ssl_timeout]
http.verify_mode = @ssl_options[:verify_mode] if @ssl_options[:verify_mode]
http.verify_callback = @ssl_options[:verify_callback] if @ssl_options[:verify_callback]
http.verify_depth = @ssl_options[:verify_depth] if @ssl_options[:verify_depth]
http
end
def default_header
@default_header ||= {}
end
# Builds headers for request to remote service.
def build_request_headers(headers, http_method=nil)
authorization_header.update(default_header).update(http_format_header(http_method)).update(headers)
end
# Sets authorization header
def authorization_header
(@user || @password ? { 'Authorization' => 'Basic ' + ["#{@user}:#{ @password}"].pack('m').delete("\r\n") } : {})
end
def http_format_header(http_method)
{HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type}
end
def logger #:nodoc:
Base.logger
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/formats.rb | provider/vendor/rails/activeresource/lib/active_resource/formats.rb | module ActiveResource
module Formats
# Lookup the format class from a mime type reference symbol. Example:
#
# ActiveResource::Formats[:xml] # => ActiveResource::Formats::XmlFormat
# ActiveResource::Formats[:json] # => ActiveResource::Formats::JsonFormat
def self.[](mime_type_reference)
ActiveResource::Formats.const_get(mime_type_reference.to_s.camelize + "Format")
end
end
end
require 'active_resource/formats/xml_format'
require 'active_resource/formats/json_format' | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/formats/json_format.rb | provider/vendor/rails/activeresource/lib/active_resource/formats/json_format.rb | module ActiveResource
module Formats
module JsonFormat
extend self
def extension
"json"
end
def mime_type
"application/json"
end
def encode(hash, options = nil)
ActiveSupport::JSON.encode(hash, options)
end
def decode(json)
ActiveSupport::JSON.decode(json)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activeresource/lib/active_resource/formats/xml_format.rb | provider/vendor/rails/activeresource/lib/active_resource/formats/xml_format.rb | module ActiveResource
module Formats
module XmlFormat
extend self
def extension
"xml"
end
def mime_type
"application/xml"
end
def encode(hash, options={})
hash.to_xml(options)
end
def decode(xml)
from_xml_data(Hash.from_xml(xml))
end
private
# Manipulate from_xml Hash, because xml_simple is not exactly what we
# want for Active Resource.
def from_xml_data(data)
if data.is_a?(Hash) && data.keys.size == 1
data.values.first
else
data
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/install.rb | provider/vendor/rails/actionmailer/install.rb | require 'rbconfig'
require 'find'
require 'ftools'
include Config
# this was adapted from rdoc's install.rb by way of Log4r
$sitedir = CONFIG["sitelibdir"]
unless $sitedir
version = CONFIG["MAJOR"] + "." + CONFIG["MINOR"]
$libdir = File.join(CONFIG["libdir"], "ruby", version)
$sitedir = $:.find {|x| x =~ /site_ruby/ }
if !$sitedir
$sitedir = File.join($libdir, "site_ruby")
elsif $sitedir !~ Regexp.quote(version)
$sitedir = File.join($sitedir, version)
end
end
# the actual gruntwork
Dir.chdir("lib")
Find.find("action_mailer", "action_mailer.rb") { |f|
if f[-3..-1] == ".rb"
File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true)
else
File::makedirs(File.join($sitedir, *f.split(/\//)))
end
}
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/mail_helper_test.rb | provider/vendor/rails/actionmailer/test/mail_helper_test.rb | require 'abstract_unit'
module MailerHelper
def person_name
"Mr. Joe Person"
end
end
class HelperMailer < ActionMailer::Base
helper MailerHelper
helper :example
def use_helper(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
end
def use_example_helper(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
self.body = { :text => "emphasize me!" }
end
def use_mail_helper(recipient)
recipients recipient
subject "using mailing helpers"
from "tester@example.com"
self.body = { :text =>
"But soft! What light through yonder window breaks? It is the east, " +
"and Juliet is the sun. Arise, fair sun, and kill the envious moon, " +
"which is sick and pale with grief that thou, her maid, art far more " +
"fair than she. Be not her maid, for she is envious! Her vestal " +
"livery is but sick and green, and none but fools do wear it. Cast " +
"it off!"
}
end
def use_helper_method(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
self.body = { :text => "emphasize me!" }
end
private
def name_of_the_mailer_class
self.class.name
end
helper_method :name_of_the_mailer_class
end
class MailerHelperTest < Test::Unit::TestCase
def new_mail( charset="utf-8" )
mail = TMail::Mail.new
mail.set_content_type "text", "plain", { "charset" => charset } if charset
mail
end
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_use_helper
mail = HelperMailer.create_use_helper(@recipient)
assert_match %r{Mr. Joe Person}, mail.encoded
end
def test_use_example_helper
mail = HelperMailer.create_use_example_helper(@recipient)
assert_match %r{<em><strong><small>emphasize me!}, mail.encoded
end
def test_use_helper_method
mail = HelperMailer.create_use_helper_method(@recipient)
assert_match %r{HelperMailer}, mail.encoded
end
def test_use_mail_helper
mail = HelperMailer.create_use_mail_helper(@recipient)
assert_match %r{ But soft!}, mail.encoded
assert_match %r{east, and\n Juliet}, mail.encoded
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/mail_layout_test.rb | provider/vendor/rails/actionmailer/test/mail_layout_test.rb | require 'abstract_unit'
class AutoLayoutMailer < ActionMailer::Base
def hello(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
end
def spam(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :layout => 'spam', :body => { :world => "Earth" })
end
def nolayout(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :layout => false, :body => { :world => "Earth" })
end
def multipart(recipient, type = nil)
recipients recipient
subject "You have a mail"
from "tester@example.com"
content_type(type) if type
end
end
class ExplicitLayoutMailer < ActionMailer::Base
layout 'spam', :except => [:logout]
def signup(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
end
def logout(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
end
end
class LayoutMailerTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_should_pickup_default_layout
mail = AutoLayoutMailer.create_hello(@recipient)
assert_equal "Hello from layout Inside", mail.body.strip
end
def test_should_pickup_multipart_layout
mail = AutoLayoutMailer.create_multipart(@recipient)
assert_equal "multipart/alternative", mail.content_type
assert_equal 2, mail.parts.size
assert_equal 'text/plain', mail.parts.first.content_type
assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
assert_equal 'text/html', mail.parts.last.content_type
assert_equal "Hello from layout text/html multipart", mail.parts.last.body
end
def test_should_pickup_multipartmixed_layout
mail = AutoLayoutMailer.create_multipart(@recipient, "multipart/mixed")
assert_equal "multipart/mixed", mail.content_type
assert_equal 2, mail.parts.size
assert_equal 'text/plain', mail.parts.first.content_type
assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
assert_equal 'text/html', mail.parts.last.content_type
assert_equal "Hello from layout text/html multipart", mail.parts.last.body
end
def test_should_fix_multipart_layout
mail = AutoLayoutMailer.create_multipart(@recipient, "text/plain")
assert_equal "multipart/alternative", mail.content_type
assert_equal 2, mail.parts.size
assert_equal 'text/plain', mail.parts.first.content_type
assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
assert_equal 'text/html', mail.parts.last.content_type
assert_equal "Hello from layout text/html multipart", mail.parts.last.body
end
def test_should_pickup_layout_given_to_render
mail = AutoLayoutMailer.create_spam(@recipient)
assert_equal "Spammer layout Hello, Earth", mail.body.strip
end
def test_should_respect_layout_false
mail = AutoLayoutMailer.create_nolayout(@recipient)
assert_equal "Hello, Earth", mail.body.strip
end
def test_explicit_class_layout
mail = ExplicitLayoutMailer.create_signup(@recipient)
assert_equal "Spammer layout We do not spam", mail.body.strip
end
def test_explicit_layout_exceptions
mail = ExplicitLayoutMailer.create_logout(@recipient)
assert_equal "You logged out", mail.body.strip
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/tmail_test.rb | provider/vendor/rails/actionmailer/test/tmail_test.rb | require 'abstract_unit'
class TMailMailTest < Test::Unit::TestCase
def test_body
m = TMail::Mail.new
expected = 'something_with_underscores'
m.encoding = 'quoted-printable'
quoted_body = [expected].pack('*M')
m.body = quoted_body
assert_equal "something_with_underscores=\n", m.quoted_body
assert_equal expected, m.body
end
def test_nested_attachments_are_recognized_correctly
fixture = File.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_nested_attachment")
mail = TMail::Mail.parse(fixture)
assert_equal 2, mail.attachments.length
assert_equal "image/png", mail.attachments.first.content_type
assert_equal 1902, mail.attachments.first.length
assert_equal "application/pkcs7-signature", mail.attachments.last.content_type
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/test_helper_test.rb | provider/vendor/rails/actionmailer/test/test_helper_test.rb | require 'abstract_unit'
class TestHelperMailer < ActionMailer::Base
def test
recipients "test@example.com"
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :body => { :world => "Earth" })
end
end
class TestHelperMailerTest < ActionMailer::TestCase
def test_setup_sets_right_action_mailer_options
assert_equal :test, ActionMailer::Base.delivery_method
assert ActionMailer::Base.perform_deliveries
assert_equal [], ActionMailer::Base.deliveries
end
def test_setup_creates_the_expected_mailer
assert @expected.is_a?(TMail::Mail)
assert_equal "1.0", @expected.mime_version
assert_equal "text/plain", @expected.content_type
end
def test_mailer_class_is_correctly_inferred
assert_equal TestHelperMailer, self.class.mailer_class
end
def test_determine_default_mailer_raises_correct_error
assert_raise(ActionMailer::NonInferrableMailerError) do
self.class.determine_default_mailer("NotAMailerTest")
end
end
def test_charset_is_utf_8
assert_equal "utf-8", charset
end
def test_encode
assert_equal "=?utf-8?Q?=0Aasdf=0A?=", encode("\nasdf\n")
end
def test_assert_emails
assert_nothing_raised do
assert_emails 1 do
TestHelperMailer.deliver_test
end
end
end
def test_repeated_assert_emails_calls
assert_nothing_raised do
assert_emails 1 do
TestHelperMailer.deliver_test
end
end
assert_nothing_raised do
assert_emails 2 do
TestHelperMailer.deliver_test
TestHelperMailer.deliver_test
end
end
end
def test_assert_emails_with_no_block
assert_nothing_raised do
TestHelperMailer.deliver_test
assert_emails 1
end
assert_nothing_raised do
TestHelperMailer.deliver_test
TestHelperMailer.deliver_test
assert_emails 3
end
end
def test_assert_no_emails
assert_nothing_raised do
assert_no_emails do
TestHelperMailer.create_test
end
end
end
def test_assert_emails_too_few_sent
error = assert_raise ActiveSupport::TestCase::Assertion do
assert_emails 2 do
TestHelperMailer.deliver_test
end
end
assert_match /2 .* but 1/, error.message
end
def test_assert_emails_too_many_sent
error = assert_raise ActiveSupport::TestCase::Assertion do
assert_emails 1 do
TestHelperMailer.deliver_test
TestHelperMailer.deliver_test
end
end
assert_match /1 .* but 2/, error.message
end
def test_assert_no_emails_failure
error = assert_raise ActiveSupport::TestCase::Assertion do
assert_no_emails do
TestHelperMailer.deliver_test
end
end
assert_match /0 .* but 1/, error.message
end
end
class AnotherTestHelperMailerTest < ActionMailer::TestCase
tests TestHelperMailer
def setup
@test_var = "a value"
end
def test_setup_shouldnt_conflict_with_mailer_setup
assert @expected.is_a?(TMail::Mail)
assert_equal 'a value', @test_var
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/delivery_method_test.rb | provider/vendor/rails/actionmailer/test/delivery_method_test.rb | require 'abstract_unit'
class DefaultDeliveryMethodMailer < ActionMailer::Base
end
class NonDefaultDeliveryMethodMailer < ActionMailer::Base
self.delivery_method = :sendmail
end
class ActionMailerBase_delivery_method_Test < Test::Unit::TestCase
def setup
set_delivery_method :smtp
end
def teardown
restore_delivery_method
end
def test_should_be_the_default_smtp
assert_equal :smtp, ActionMailer::Base.delivery_method
end
end
class DefaultDeliveryMethodMailer_delivery_method_Test < Test::Unit::TestCase
def setup
set_delivery_method :smtp
end
def teardown
restore_delivery_method
end
def test_should_be_the_default_smtp
assert_equal :smtp, DefaultDeliveryMethodMailer.delivery_method
end
end
class NonDefaultDeliveryMethodMailer_delivery_method_Test < Test::Unit::TestCase
def setup
set_delivery_method :smtp
end
def teardown
restore_delivery_method
end
def test_should_be_the_set_delivery_method
assert_equal :sendmail, NonDefaultDeliveryMethodMailer.delivery_method
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/mail_service_test.rb | provider/vendor/rails/actionmailer/test/mail_service_test.rb | # encoding: utf-8
require 'abstract_unit'
class FunkyPathMailer < ActionMailer::Base
self.template_root = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
def multipart_with_template_path_with_dots(recipient)
recipients recipient
subject "Have a lovely picture"
from "Chad Fowler <chad@chadfowler.com>"
attachment :content_type => "image/jpeg",
:body => "not really a jpeg, we're only testing, after all"
end
end
class TestMailer < ActionMailer::Base
def signed_up(recipient)
@recipients = recipient
@subject = "[Signed up] Welcome #{recipient}"
@from = "system@loudthinking.com"
@body["recipient"] = recipient
end
def cancelled_account(recipient)
self.recipients = recipient
self.subject = "[Cancelled] Goodbye #{recipient}"
self.from = "system@loudthinking.com"
self.sent_on = Time.local(2004, 12, 12)
self.body = "Goodbye, Mr. #{recipient}"
end
def cc_bcc(recipient)
recipients recipient
subject "testing bcc/cc"
from "system@loudthinking.com"
sent_on Time.local(2004, 12, 12)
cc "nobody@loudthinking.com"
bcc "root@loudthinking.com"
body "Nothing to see here."
end
def different_reply_to(recipient)
recipients recipient
subject "testing reply_to"
from "system@loudthinking.com"
sent_on Time.local(2008, 5, 23)
reply_to "atraver@gmail.com"
body "Nothing to see here."
end
def iso_charset(recipient)
@recipients = recipient
@subject = "testing isø charsets"
@from = "system@loudthinking.com"
@sent_on = Time.local 2004, 12, 12
@cc = "nobody@loudthinking.com"
@bcc = "root@loudthinking.com"
@body = "Nothing to see here."
@charset = "iso-8859-1"
end
def unencoded_subject(recipient)
@recipients = recipient
@subject = "testing unencoded subject"
@from = "system@loudthinking.com"
@sent_on = Time.local 2004, 12, 12
@cc = "nobody@loudthinking.com"
@bcc = "root@loudthinking.com"
@body = "Nothing to see here."
end
def extended_headers(recipient)
@recipients = recipient
@subject = "testing extended headers"
@from = "Grytøyr <stian1@example.net>"
@sent_on = Time.local 2004, 12, 12
@cc = "Grytøyr <stian2@example.net>"
@bcc = "Grytøyr <stian3@example.net>"
@body = "Nothing to see here."
@charset = "iso-8859-1"
end
def utf8_body(recipient)
@recipients = recipient
@subject = "testing utf-8 body"
@from = "Foo áëô îü <extended@example.net>"
@sent_on = Time.local 2004, 12, 12
@cc = "Foo áëô îü <extended@example.net>"
@bcc = "Foo áëô îü <extended@example.net>"
@body = "åœö blah"
@charset = "utf-8"
end
def multipart_with_mime_version(recipient)
recipients recipient
subject "multipart with mime_version"
from "test@example.com"
sent_on Time.local(2004, 12, 12)
mime_version "1.1"
content_type "multipart/alternative"
part "text/plain" do |p|
p.body = "blah"
end
part "text/html" do |p|
p.body = "<b>blah</b>"
end
end
def multipart_with_utf8_subject(recipient)
recipients recipient
subject "Foo áëô îü"
from "test@example.com"
charset "utf-8"
part "text/plain" do |p|
p.body = "blah"
end
part "text/html" do |p|
p.body = "<b>blah</b>"
end
end
def explicitly_multipart_example(recipient, ct=nil)
recipients recipient
subject "multipart example"
from "test@example.com"
sent_on Time.local(2004, 12, 12)
body "plain text default"
content_type ct if ct
part "text/html" do |p|
p.charset = "iso-8859-1"
p.body = "blah"
end
attachment :content_type => "image/jpeg", :filename => "foo.jpg",
:body => "123456789"
end
def implicitly_multipart_example(recipient, cs = nil, order = nil)
@recipients = recipient
@subject = "multipart example"
@from = "test@example.com"
@sent_on = Time.local 2004, 12, 12
@body = { "recipient" => recipient }
@charset = cs if cs
@implicit_parts_order = order if order
end
def implicitly_multipart_with_utf8
recipients "no.one@nowhere.test"
subject "Foo áëô îü"
from "some.one@somewhere.test"
template "implicitly_multipart_example"
body ({ "recipient" => "no.one@nowhere.test" })
end
def html_mail(recipient)
recipients recipient
subject "html mail"
from "test@example.com"
body "<em>Emphasize</em> <strong>this</strong>"
content_type "text/html"
end
def html_mail_with_underscores(recipient)
subject "html mail with underscores"
body %{<a href="http://google.com" target="_blank">_Google</a>}
end
def custom_template(recipient)
recipients recipient
subject "[Signed up] Welcome #{recipient}"
from "system@loudthinking.com"
sent_on Time.local(2004, 12, 12)
template "signed_up"
body["recipient"] = recipient
end
def custom_templating_extension(recipient)
recipients recipient
subject "[Signed up] Welcome #{recipient}"
from "system@loudthinking.com"
sent_on Time.local(2004, 12, 12)
body["recipient"] = recipient
end
def various_newlines(recipient)
recipients recipient
subject "various newlines"
from "test@example.com"
body "line #1\nline #2\rline #3\r\nline #4\r\r" +
"line #5\n\nline#6\r\n\r\nline #7"
end
def various_newlines_multipart(recipient)
recipients recipient
subject "various newlines multipart"
from "test@example.com"
content_type "multipart/alternative"
part :content_type => "text/plain", :body => "line #1\nline #2\rline #3\r\nline #4\r\r"
part :content_type => "text/html", :body => "<p>line #1</p>\n<p>line #2</p>\r<p>line #3</p>\r\n<p>line #4</p>\r\r"
end
def nested_multipart(recipient)
recipients recipient
subject "nested multipart"
from "test@example.com"
content_type "multipart/mixed"
part :content_type => "multipart/alternative", :content_disposition => "inline", :headers => { "foo" => "bar" } do |p|
p.part :content_type => "text/plain", :body => "test text\nline #2"
p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
end
attachment :content_type => "application/octet-stream",:filename => "test.txt", :body => "test abcdefghijklmnopqstuvwxyz"
end
def nested_multipart_with_body(recipient)
recipients recipient
subject "nested multipart with body"
from "test@example.com"
content_type "multipart/mixed"
part :content_type => "multipart/alternative", :content_disposition => "inline", :body => "Nothing to see here." do |p|
p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>"
end
end
def attachment_with_custom_header(recipient)
recipients recipient
subject "custom header in attachment"
from "test@example.com"
content_type "multipart/related"
part :content_type => "text/html", :body => 'yo'
attachment :content_type => "image/jpeg",:filename => "test.jpeg", :body => "i am not a real picture", :headers => { 'Content-ID' => '<test@test.com>' }
end
def unnamed_attachment(recipient)
recipients recipient
subject "nested multipart"
from "test@example.com"
content_type "multipart/mixed"
part :content_type => "text/plain", :body => "hullo"
attachment :content_type => "application/octet-stream", :body => "test abcdefghijklmnopqstuvwxyz"
end
def headers_with_nonalpha_chars(recipient)
recipients recipient
subject "nonalpha chars"
from "One: Two <test@example.com>"
cc "Three: Four <test@example.com>"
bcc "Five: Six <test@example.com>"
body "testing"
end
def custom_content_type_attributes
recipients "no.one@nowhere.test"
subject "custom content types"
from "some.one@somewhere.test"
content_type "text/plain; format=flowed"
body "testing"
end
def return_path
recipients "no.one@nowhere.test"
subject "return path test"
from "some.one@somewhere.test"
body "testing"
headers "return-path" => "another@somewhere.test"
end
def body_ivar(recipient)
recipients recipient
subject "Body as a local variable"
from "test@example.com"
body :body => "foo", :bar => "baz"
end
class <<self
attr_accessor :received_body
end
def receive(mail)
self.class.received_body = mail.body
end
end
class ActionMailerTest < Test::Unit::TestCase
include ActionMailer::Quoting
def encode( text, charset="utf-8" )
quoted_printable( text, charset )
end
def new_mail( charset="utf-8" )
mail = TMail::Mail.new
mail.mime_version = "1.0"
if charset
mail.set_content_type "text", "plain", { "charset" => charset }
end
mail
end
# Replacing logger work around for mocha bug. Should be fixed in mocha 0.3.3
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.deliveries = []
@original_logger = TestMailer.logger
@recipient = 'test@localhost'
end
def teardown
TestMailer.logger = @original_logger
restore_delivery_method
end
def test_nested_parts
created = nil
assert_nothing_raised { created = TestMailer.create_nested_multipart(@recipient)}
assert_equal 2,created.parts.size
assert_equal 2,created.parts.first.parts.size
assert_equal "multipart/mixed", created.content_type
assert_equal "multipart/alternative", created.parts.first.content_type
assert_equal "bar", created.parts.first.header['foo'].to_s
assert_nil created.parts.first.charset
assert_equal "text/plain", created.parts.first.parts.first.content_type
assert_equal "text/html", created.parts.first.parts[1].content_type
assert_equal "application/octet-stream", created.parts[1].content_type
end
def test_nested_parts_with_body
created = nil
assert_nothing_raised { created = TestMailer.create_nested_multipart_with_body(@recipient)}
assert_equal 1,created.parts.size
assert_equal 2,created.parts.first.parts.size
assert_equal "multipart/mixed", created.content_type
assert_equal "multipart/alternative", created.parts.first.content_type
assert_equal "Nothing to see here.", created.parts.first.parts.first.body
assert_equal "text/plain", created.parts.first.parts.first.content_type
assert_equal "text/html", created.parts.first.parts[1].content_type
end
def test_attachment_with_custom_header
created = nil
assert_nothing_raised { created = TestMailer.create_attachment_with_custom_header(@recipient)}
assert_equal "<test@test.com>", created.parts[1].header['content-id'].to_s
end
def test_signed_up
Time.stubs(:now => Time.now)
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
expected.body = "Hello there, \n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.now
created = nil
assert_nothing_raised { created = TestMailer.create_signed_up(@recipient) }
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised { TestMailer.deliver_signed_up(@recipient) }
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_custom_template
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
expected.body = "Hello there, \n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
created = nil
assert_nothing_raised { created = TestMailer.create_custom_template(@recipient) }
assert_not_nil created
assert_equal expected.encoded, created.encoded
end
def test_custom_templating_extension
assert ActionView::Template.template_handler_extensions.include?("haml"), "haml extension was not registered"
# N.b., custom_templating_extension.text.plain.haml is expected to be in fixtures/test_mailer directory
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
expected.body = "Hello there, \n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
# Stub the render method so no alternative renderers need be present.
ActionView::Base.any_instance.stubs(:render).returns("Hello there, \n\nMr. #{@recipient}")
# Now that the template is registered, there should be one part. The text/plain part.
created = nil
assert_nothing_raised { created = TestMailer.create_custom_templating_extension(@recipient) }
assert_not_nil created
assert_equal 2, created.parts.length
assert_equal 'text/plain', created.parts[0].content_type
assert_equal 'text/html', created.parts[1].content_type
end
def test_cancelled_account
expected = new_mail
expected.to = @recipient
expected.subject = "[Cancelled] Goodbye #{@recipient}"
expected.body = "Goodbye, Mr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
created = nil
assert_nothing_raised { created = TestMailer.create_cancelled_account(@recipient) }
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised { TestMailer.deliver_cancelled_account(@recipient) }
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_cc_bcc
expected = new_mail
expected.to = @recipient
expected.subject = "testing bcc/cc"
expected.body = "Nothing to see here."
expected.from = "system@loudthinking.com"
expected.cc = "nobody@loudthinking.com"
expected.bcc = "root@loudthinking.com"
expected.date = Time.local 2004, 12, 12
created = nil
assert_nothing_raised do
created = TestMailer.create_cc_bcc @recipient
end
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
TestMailer.deliver_cc_bcc @recipient
end
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_reply_to
expected = new_mail
expected.to = @recipient
expected.subject = "testing reply_to"
expected.body = "Nothing to see here."
expected.from = "system@loudthinking.com"
expected.reply_to = "atraver@gmail.com"
expected.date = Time.local 2008, 5, 23
created = nil
assert_nothing_raised do
created = TestMailer.create_different_reply_to @recipient
end
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
TestMailer.deliver_different_reply_to @recipient
end
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_iso_charset
expected = new_mail( "iso-8859-1" )
expected.to = @recipient
expected.subject = encode "testing isø charsets", "iso-8859-1"
expected.body = "Nothing to see here."
expected.from = "system@loudthinking.com"
expected.cc = "nobody@loudthinking.com"
expected.bcc = "root@loudthinking.com"
expected.date = Time.local 2004, 12, 12
created = nil
assert_nothing_raised do
created = TestMailer.create_iso_charset @recipient
end
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
TestMailer.deliver_iso_charset @recipient
end
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_unencoded_subject
expected = new_mail
expected.to = @recipient
expected.subject = "testing unencoded subject"
expected.body = "Nothing to see here."
expected.from = "system@loudthinking.com"
expected.cc = "nobody@loudthinking.com"
expected.bcc = "root@loudthinking.com"
expected.date = Time.local 2004, 12, 12
created = nil
assert_nothing_raised do
created = TestMailer.create_unencoded_subject @recipient
end
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
TestMailer.deliver_unencoded_subject @recipient
end
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_instances_are_nil
assert_nil ActionMailer::Base.new
assert_nil TestMailer.new
end
def test_deliveries_array
assert_not_nil ActionMailer::Base.deliveries
assert_equal 0, ActionMailer::Base.deliveries.size
TestMailer.deliver_signed_up(@recipient)
assert_equal 1, ActionMailer::Base.deliveries.size
assert_not_nil ActionMailer::Base.deliveries.first
end
def test_perform_deliveries_flag
ActionMailer::Base.perform_deliveries = false
TestMailer.deliver_signed_up(@recipient)
assert_equal 0, ActionMailer::Base.deliveries.size
ActionMailer::Base.perform_deliveries = true
TestMailer.deliver_signed_up(@recipient)
assert_equal 1, ActionMailer::Base.deliveries.size
end
def test_doesnt_raise_errors_when_raise_delivery_errors_is_false
ActionMailer::Base.raise_delivery_errors = false
TestMailer.any_instance.expects(:perform_delivery_test).raises(Exception)
assert_nothing_raised { TestMailer.deliver_signed_up(@recipient) }
end
def test_performs_delivery_via_sendmail
sm = mock()
sm.expects(:print).with(anything)
sm.expects(:flush)
IO.expects(:popen).once.with('/usr/sbin/sendmail -i -t', 'w+').yields(sm)
ActionMailer::Base.delivery_method = :sendmail
TestMailer.deliver_signed_up(@recipient)
end
def test_delivery_logs_sent_mail
mail = TestMailer.create_signed_up(@recipient)
logger = mock()
logger.expects(:info).with("Sent mail to #{@recipient}")
logger.expects(:debug).with("\n#{mail.encoded}")
TestMailer.logger = logger
TestMailer.deliver_signed_up(@recipient)
end
def test_unquote_quoted_printable_subject
msg = <<EOF
From: me@example.com
Subject: =?utf-8?Q?testing_testing_=D6=A4?=
Content-Type: text/plain; charset=iso-8859-1
The body
EOF
mail = TMail::Mail.parse(msg)
assert_equal "testing testing \326\244", mail.subject
assert_equal "=?utf-8?Q?testing_testing_=D6=A4?=", mail.quoted_subject
end
def test_unquote_7bit_subject
msg = <<EOF
From: me@example.com
Subject: this == working?
Content-Type: text/plain; charset=iso-8859-1
The body
EOF
mail = TMail::Mail.parse(msg)
assert_equal "this == working?", mail.subject
assert_equal "this == working?", mail.quoted_subject
end
def test_unquote_7bit_body
msg = <<EOF
From: me@example.com
Subject: subject
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
The=3Dbody
EOF
mail = TMail::Mail.parse(msg)
assert_equal "The=3Dbody", mail.body.strip
assert_equal "The=3Dbody", mail.quoted_body.strip
end
def test_unquote_quoted_printable_body
msg = <<EOF
From: me@example.com
Subject: subject
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
The=3Dbody
EOF
mail = TMail::Mail.parse(msg)
assert_equal "The=body", mail.body.strip
assert_equal "The=3Dbody", mail.quoted_body.strip
end
def test_unquote_base64_body
msg = <<EOF
From: me@example.com
Subject: subject
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: base64
VGhlIGJvZHk=
EOF
mail = TMail::Mail.parse(msg)
assert_equal "The body", mail.body.strip
assert_equal "VGhlIGJvZHk=", mail.quoted_body.strip
end
def test_extended_headers
@recipient = "Grytøyr <test@localhost>"
expected = new_mail "iso-8859-1"
expected.to = quote_address_if_necessary @recipient, "iso-8859-1"
expected.subject = "testing extended headers"
expected.body = "Nothing to see here."
expected.from = quote_address_if_necessary "Grytøyr <stian1@example.net>", "iso-8859-1"
expected.cc = quote_address_if_necessary "Grytøyr <stian2@example.net>", "iso-8859-1"
expected.bcc = quote_address_if_necessary "Grytøyr <stian3@example.net>", "iso-8859-1"
expected.date = Time.local 2004, 12, 12
created = nil
assert_nothing_raised do
created = TestMailer.create_extended_headers @recipient
end
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
TestMailer.deliver_extended_headers @recipient
end
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
def test_utf8_body_is_not_quoted
@recipient = "Foo áëô îü <extended@example.net>"
expected = new_mail "utf-8"
expected.to = quote_address_if_necessary @recipient, "utf-8"
expected.subject = "testing utf-8 body"
expected.body = "åœö blah"
expected.from = quote_address_if_necessary @recipient, "utf-8"
expected.cc = quote_address_if_necessary @recipient, "utf-8"
expected.bcc = quote_address_if_necessary @recipient, "utf-8"
expected.date = Time.local 2004, 12, 12
created = TestMailer.create_utf8_body @recipient
assert_match(/åœö blah/, created.encoded)
end
def test_multiple_utf8_recipients
@recipient = ["\"Foo áëô îü\" <extended@example.net>", "\"Example Recipient\" <me@example.com>"]
expected = new_mail "utf-8"
expected.to = quote_address_if_necessary @recipient, "utf-8"
expected.subject = "testing utf-8 body"
expected.body = "åœö blah"
expected.from = quote_address_if_necessary @recipient.first, "utf-8"
expected.cc = quote_address_if_necessary @recipient, "utf-8"
expected.bcc = quote_address_if_necessary @recipient, "utf-8"
expected.date = Time.local 2004, 12, 12
created = TestMailer.create_utf8_body @recipient
assert_match(/\nFrom: =\?utf-8\?Q\?Foo_.*?\?= <extended@example.net>\r/, created.encoded)
assert_match(/\nTo: =\?utf-8\?Q\?Foo_.*?\?= <extended@example.net>, Example Recipient <me/, created.encoded)
end
def test_receive_decodes_base64_encoded_mail
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email")
TestMailer.receive(fixture)
assert_match(/Jamis/, TestMailer.received_body)
end
def test_receive_attachments
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email2")
mail = TMail::Mail.parse(fixture)
attachment = mail.attachments.last
assert_equal "smime.p7s", attachment.original_filename
assert_equal "application/pkcs7-signature", attachment.content_type
end
def test_decode_attachment_without_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email3")
mail = TMail::Mail.parse(fixture)
attachment = mail.attachments.last
assert_equal 1026, attachment.read.length
end
def test_attachment_using_content_location
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email12")
mail = TMail::Mail.parse(fixture)
assert_equal 1, mail.attachments.length
assert_equal "Photo25.jpg", mail.attachments.first.original_filename
end
def test_attachment_with_text_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email13")
mail = TMail::Mail.parse(fixture)
assert mail.has_attachments?
assert_equal 1, mail.attachments.length
assert_equal "hello.rb", mail.attachments.first.original_filename
end
def test_decode_part_without_content_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email4")
mail = TMail::Mail.parse(fixture)
assert_nothing_raised { mail.body }
end
def test_decode_message_without_content_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email5")
mail = TMail::Mail.parse(fixture)
assert_nothing_raised { mail.body }
end
def test_decode_message_with_incorrect_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email6")
mail = TMail::Mail.parse(fixture)
assert_nothing_raised { mail.body }
end
def test_multipart_with_mime_version
mail = TestMailer.create_multipart_with_mime_version(@recipient)
assert_equal "1.1", mail.mime_version
end
def test_multipart_with_utf8_subject
mail = TestMailer.create_multipart_with_utf8_subject(@recipient)
assert_match(/\nSubject: =\?utf-8\?Q\?Foo_.*?\?=/, mail.encoded)
end
def test_implicitly_multipart_with_utf8
mail = TestMailer.create_implicitly_multipart_with_utf8
assert_match(/\nSubject: =\?utf-8\?Q\?Foo_.*?\?=/, mail.encoded)
end
def test_explicitly_multipart_messages
mail = TestMailer.create_explicitly_multipart_example(@recipient)
assert_equal 3, mail.parts.length
assert_nil mail.content_type
assert_equal "text/plain", mail.parts[0].content_type
assert_equal "text/html", mail.parts[1].content_type
assert_equal "iso-8859-1", mail.parts[1].sub_header("content-type", "charset")
assert_equal "inline", mail.parts[1].content_disposition
assert_equal "image/jpeg", mail.parts[2].content_type
assert_equal "attachment", mail.parts[2].content_disposition
assert_equal "foo.jpg", mail.parts[2].sub_header("content-disposition", "filename")
assert_equal "foo.jpg", mail.parts[2].sub_header("content-type", "name")
assert_nil mail.parts[2].sub_header("content-type", "charset")
end
def test_explicitly_multipart_with_content_type
mail = TestMailer.create_explicitly_multipart_example(@recipient, "multipart/alternative")
assert_equal 3, mail.parts.length
assert_equal "multipart/alternative", mail.content_type
end
def test_explicitly_multipart_with_invalid_content_type
mail = TestMailer.create_explicitly_multipart_example(@recipient, "text/xml")
assert_equal 3, mail.parts.length
assert_nil mail.content_type
end
def test_implicitly_multipart_messages
assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered"
mail = TestMailer.create_implicitly_multipart_example(@recipient)
assert_equal 3, mail.parts.length
assert_equal "1.0", mail.mime_version
assert_equal "multipart/alternative", mail.content_type
assert_equal "text/yaml", mail.parts[0].content_type
assert_equal "utf-8", mail.parts[0].sub_header("content-type", "charset")
assert_equal "text/plain", mail.parts[1].content_type
assert_equal "utf-8", mail.parts[1].sub_header("content-type", "charset")
assert_equal "text/html", mail.parts[2].content_type
assert_equal "utf-8", mail.parts[2].sub_header("content-type", "charset")
end
def test_implicitly_multipart_messages_with_custom_order
assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered"
mail = TestMailer.create_implicitly_multipart_example(@recipient, nil, ["text/yaml", "text/plain"])
assert_equal 3, mail.parts.length
assert_equal "text/html", mail.parts[0].content_type
assert_equal "text/plain", mail.parts[1].content_type
assert_equal "text/yaml", mail.parts[2].content_type
end
def test_implicitly_multipart_messages_with_charset
mail = TestMailer.create_implicitly_multipart_example(@recipient, 'iso-8859-1')
assert_equal "multipart/alternative", mail.header['content-type'].body
assert_equal 'iso-8859-1', mail.parts[0].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[1].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[2].sub_header("content-type", "charset")
end
def test_html_mail
mail = TestMailer.create_html_mail(@recipient)
assert_equal "text/html", mail.content_type
end
def test_html_mail_with_underscores
mail = TestMailer.create_html_mail_with_underscores(@recipient)
assert_equal %{<a href="http://google.com" target="_blank">_Google</a>}, mail.body
end
def test_various_newlines
mail = TestMailer.create_various_newlines(@recipient)
assert_equal("line #1\nline #2\nline #3\nline #4\n\n" +
"line #5\n\nline#6\n\nline #7", mail.body)
end
def test_various_newlines_multipart
mail = TestMailer.create_various_newlines_multipart(@recipient)
assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body
assert_equal "<p>line #1</p>\n<p>line #2</p>\n<p>line #3</p>\n<p>line #4</p>\n\n", mail.parts[1].body
end
def test_headers_removed_on_smtp_delivery
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_cc_bcc(@recipient)
assert MockSMTP.deliveries[0][2].include?("root@loudthinking.com")
assert MockSMTP.deliveries[0][2].include?("nobody@loudthinking.com")
assert MockSMTP.deliveries[0][2].include?(@recipient)
assert_match %r{^Cc: nobody@loudthinking.com}, MockSMTP.deliveries[0][0]
assert_match %r{^To: #{@recipient}}, MockSMTP.deliveries[0][0]
assert_no_match %r{^Bcc: root@loudthinking.com}, MockSMTP.deliveries[0][0]
end
def test_recursive_multipart_processing
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email7")
mail = TMail::Mail.parse(fixture)
assert_equal "This is the first part.\n\nAttachment: test.rb\nAttachment: test.pdf\n\n\nAttachment: smime.p7s\n", mail.body
end
def test_decode_encoded_attachment_filename
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email8")
mail = TMail::Mail.parse(fixture)
attachment = mail.attachments.last
expected = "01 Quien Te Dij\212at. Pitbull.mp3"
expected.force_encoding(Encoding::ASCII_8BIT) if expected.respond_to?(:force_encoding)
assert_equal expected, attachment.original_filename
end
def test_wrong_mail_header
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email9")
assert_raise(TMail::SyntaxError) { TMail::Mail.parse(fixture) }
end
def test_decode_message_with_unknown_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email10")
mail = TMail::Mail.parse(fixture)
assert_nothing_raised { mail.body }
end
def test_empty_header_values_omitted
result = TestMailer.create_unnamed_attachment(@recipient).encoded
assert_match %r{Content-Type: application/octet-stream[^;]}, result
assert_match %r{Content-Disposition: attachment[^;]}, result
end
def test_headers_with_nonalpha_chars
mail = TestMailer.create_headers_with_nonalpha_chars(@recipient)
assert !mail.from_addrs.empty?
assert !mail.cc_addrs.empty?
assert !mail.bcc_addrs.empty?
assert_match(/:/, mail.from_addrs.to_s)
assert_match(/:/, mail.cc_addrs.to_s)
assert_match(/:/, mail.bcc_addrs.to_s)
end
def test_deliver_with_mail_object
mail = TestMailer.create_headers_with_nonalpha_chars(@recipient)
assert_nothing_raised { TestMailer.deliver(mail) }
assert_equal 1, TestMailer.deliveries.length
end
def test_multipart_with_template_path_with_dots
mail = FunkyPathMailer.create_multipart_with_template_path_with_dots(@recipient)
assert_equal 2, mail.parts.length
assert_equal 'text/plain', mail.parts[0].content_type
assert_equal 'utf-8', mail.parts[0].charset
end
def test_custom_content_type_attributes
mail = TestMailer.create_custom_content_type_attributes
assert_match %r{format=flowed}, mail['content-type'].to_s
assert_match %r{charset=utf-8}, mail['content-type'].to_s
end
def test_return_path_with_create
mail = TestMailer.create_return_path
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/mail_render_test.rb | provider/vendor/rails/actionmailer/test/mail_render_test.rb | require 'abstract_unit'
class RenderMailer < ActionMailer::Base
def inline_template(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :body => { :world => "Earth" })
end
def file_template(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
body render(:file => "signed_up", :body => { :recipient => recipient })
end
def rxml_template(recipient)
recipients recipient
subject "rendering rxml template"
from "tester@example.com"
end
def included_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
from "tester@example.com"
end
def included_old_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
from "tester@example.com"
body render(:inline => "Hello, <%= render \"subtemplate\" %>", :body => { :world => "Earth" })
end
def initialize_defaults(method_name)
super
mailer_name "test_mailer"
end
end
class FirstMailer < ActionMailer::Base
def share(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
end
end
class SecondMailer < ActionMailer::Base
def share(recipient)
recipients recipient
subject "using helpers"
from "tester@example.com"
end
end
class RenderHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_inline_template
mail = RenderMailer.create_inline_template(@recipient)
assert_equal "Hello, Earth", mail.body.strip
end
def test_file_template
mail = RenderMailer.create_file_template(@recipient)
assert_equal "Hello there, \n\nMr. test@localhost", mail.body.strip
end
def test_rxml_template
mail = RenderMailer.deliver_rxml_template(@recipient)
assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test/>", mail.body.strip
end
def test_included_subtemplate
mail = RenderMailer.deliver_included_subtemplate(@recipient)
assert_equal "Hey Ho, let's go!", mail.body.strip
end
end
class FirstSecondHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_ordering
mail = FirstMailer.create_share(@recipient)
assert_equal "first mail", mail.body.strip
mail = SecondMailer.create_share(@recipient)
assert_equal "second mail", mail.body.strip
mail = FirstMailer.create_share(@recipient)
assert_equal "first mail", mail.body.strip
mail = SecondMailer.create_share(@recipient)
assert_equal "second mail", mail.body.strip
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/quoting_test.rb | provider/vendor/rails/actionmailer/test/quoting_test.rb | # encoding: utf-8
require 'abstract_unit'
require 'tempfile'
class QuotingTest < Test::Unit::TestCase
# Move some tests from TMAIL here
def test_unquote_quoted_printable
a ="=?ISO-8859-1?Q?[166417]_Bekr=E6ftelse_fra_Rejsefeber?="
b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417] Bekr\303\246ftelse fra Rejsefeber", b
end
def test_unquote_base64
a ="=?ISO-8859-1?B?WzE2NjQxN10gQmVrcuZmdGVsc2UgZnJhIFJlanNlZmViZXI=?="
b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417] Bekr\303\246ftelse fra Rejsefeber", b
end
def test_unquote_without_charset
a ="[166417]_Bekr=E6ftelse_fra_Rejsefeber"
b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417]_Bekr=E6ftelse_fra_Rejsefeber", b
end
def test_unqoute_multiple
a ="=?utf-8?q?Re=3A_=5B12=5D_=23137=3A_Inkonsistente_verwendung_von_=22Hin?==?utf-8?b?enVmw7xnZW4i?="
b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
assert_equal "Re: [12] #137: Inkonsistente verwendung von \"Hinzuf\303\274gen\"", b
end
def test_unqoute_in_the_middle
a ="Re: Photos =?ISO-8859-1?Q?Brosch=FCre_Rand?="
b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
assert_equal "Re: Photos Brosch\303\274re Rand", b
end
def test_unqoute_iso
a ="=?ISO-8859-1?Q?Brosch=FCre_Rand?="
b = TMail::Unquoter.unquote_and_convert_to(a, 'iso-8859-1')
expected = "Brosch\374re Rand"
expected.force_encoding 'iso-8859-1' if expected.respond_to?(:force_encoding)
assert_equal expected, b
end
def test_quote_multibyte_chars
original = "\303\246 \303\270 and \303\245"
original.force_encoding('ASCII-8BIT') if original.respond_to?(:force_encoding)
result = execute_in_sandbox(<<-CODE)
$:.unshift(File.dirname(__FILE__) + "/../lib/")
if RUBY_VERSION < '1.9'
$KCODE = 'u'
require 'jcode'
end
require 'action_mailer/quoting'
include ActionMailer::Quoting
quoted_printable(#{original.inspect}, "UTF-8")
CODE
unquoted = TMail::Unquoter.unquote_and_convert_to(result, nil)
assert_equal unquoted, original
end
# test an email that has been created using \r\n newlines, instead of
# \n newlines.
def test_email_quoted_with_0d0a
mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_quoted_with_0d0a"))
assert_match %r{Elapsed time}, mail.body
end
def test_email_with_partially_quoted_subject
mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_partially_quoted_subject"))
assert_equal "Re: Test: \"\346\274\242\345\255\227\" mid \"\346\274\242\345\255\227\" tail", mail.subject
end
private
# This whole thing *could* be much simpler, but I don't think Tempfile,
# popen and others exist on all platforms (like Windows).
def execute_in_sandbox(code)
test_name = "#{File.dirname(__FILE__)}/am-quoting-test.#{$$}.rb"
res_name = "#{File.dirname(__FILE__)}/am-quoting-test.#{$$}.out"
File.open(test_name, "w+") do |file|
file.write(<<-CODE)
block = Proc.new do
#{code}
end
puts block.call
CODE
end
system("ruby #{test_name} > #{res_name}") or raise "could not run test in sandbox"
File.read(res_name).chomp
ensure
File.delete(test_name) rescue nil
File.delete(res_name) rescue nil
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/abstract_unit.rb | provider/vendor/rails/actionmailer/test/abstract_unit.rb | require 'rubygems'
require 'test/unit'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
$:.unshift "#{File.dirname(__FILE__)}/../../activesupport/lib"
$:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
require 'action_mailer'
require 'action_mailer/test_case'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
# Bogus template processors
ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!".inspect }
ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup".inspect }
$:.unshift "#{File.dirname(__FILE__)}/fixtures/helpers"
ActionView::Base.cache_template_loading = true
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionMailer::Base.template_root = FIXTURE_LOAD_PATH
class MockSMTP
def self.deliveries
@@deliveries
end
def initialize
@@deliveries = []
end
def sendmail(mail, from, to)
@@deliveries << [mail, from, to]
end
def start(*args)
yield self
end
end
class Net::SMTP
def self.new(*args)
MockSMTP.new
end
end
def uses_gem(gem_name, test_name, version = '> 0')
gem gem_name.to_s, version
require gem_name.to_s
yield
rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
end
def set_delivery_method(delivery_method)
@old_delivery_method = ActionMailer::Base.delivery_method
ActionMailer::Base.delivery_method = delivery_method
end
def restore_delivery_method
ActionMailer::Base.delivery_method = @old_delivery_method
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/url_test.rb | provider/vendor/rails/actionmailer/test/url_test.rb | require 'abstract_unit'
class TestMailer < ActionMailer::Base
default_url_options[:host] = 'www.basecamphq.com'
def signed_up_with_url(recipient)
@recipients = recipient
@subject = "[Signed up] Welcome #{recipient}"
@from = "system@loudthinking.com"
@sent_on = Time.local(2004, 12, 12)
@body["recipient"] = recipient
@body["welcome_url"] = url_for :host => "example.com", :controller => "welcome", :action => "greeting"
end
class <<self
attr_accessor :received_body
end
def receive(mail)
self.class.received_body = mail.body
end
end
class ActionMailerUrlTest < Test::Unit::TestCase
include ActionMailer::Quoting
def encode( text, charset="utf-8" )
quoted_printable( text, charset )
end
def new_mail( charset="utf-8" )
mail = TMail::Mail.new
mail.mime_version = "1.0"
if charset
mail.set_content_type "text", "plain", { "charset" => charset }
end
mail
end
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_signed_up_with_url
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
map.welcome 'welcome', :controller=>"foo", :action=>"bar"
end
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
expected.body = "Hello there, \n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n<img alt=\"Somelogo\" src=\"/images/somelogo.png\" />"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
created = nil
assert_nothing_raised { created = TestMailer.create_signed_up_with_url(@recipient) }
assert_not_nil created
assert_equal expected.encoded, created.encoded
assert_nothing_raised { TestMailer.deliver_signed_up_with_url(@recipient) }
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/asset_host_test.rb | provider/vendor/rails/actionmailer/test/asset_host_test.rb | require 'abstract_unit'
class AssetHostMailer < ActionMailer::Base
def email_with_asset(recipient)
recipients recipient
subject "testing email containing asset path while asset_host is set"
from "tester@example.com"
end
end
class AssetHostTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_asset_host_as_string
ActionController::Base.asset_host = "http://www.example.com"
mail = AssetHostMailer.deliver_email_with_asset(@recipient)
assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.strip
end
def test_asset_host_as_one_arguement_proc
ActionController::Base.asset_host = Proc.new { |source|
if source.starts_with?('/images')
"http://images.example.com"
else
"http://assets.example.com"
end
}
mail = AssetHostMailer.deliver_email_with_asset(@recipient)
assert_equal "<img alt=\"Somelogo\" src=\"http://images.example.com/images/somelogo.png\" />", mail.body.strip
end
def test_asset_host_as_two_arguement_proc
ActionController::Base.asset_host = Proc.new {|source,request|
if request && request.ssl?
"https://www.example.com"
else
"http://www.example.com"
end
}
mail = nil
assert_nothing_raised { mail = AssetHostMailer.deliver_email_with_asset(@recipient) }
assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.strip
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/test/fixtures/helpers/example_helper.rb | provider/vendor/rails/actionmailer/test/fixtures/helpers/example_helper.rb | module ExampleHelper
def example_format(text)
"<em><strong><small>#{text}</small></strong></em>"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/actionmailer.rb | provider/vendor/rails/actionmailer/lib/actionmailer.rb | require 'action_mailer'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer.rb | provider/vendor/rails/actionmailer/lib/action_mailer.rb | #--
# Copyright (c) 2004-2009 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
begin
require 'action_controller'
rescue LoadError
actionpack_path = "#{File.dirname(__FILE__)}/../../actionpack/lib"
if File.directory?(actionpack_path)
$:.unshift actionpack_path
require 'action_controller'
end
end
require 'action_view'
module ActionMailer
def self.load_all!
[Base, Part, ::Text::Format, ::Net::SMTP]
end
autoload :AdvAttrAccessor, 'action_mailer/adv_attr_accessor'
autoload :Base, 'action_mailer/base'
autoload :Helpers, 'action_mailer/helpers'
autoload :Part, 'action_mailer/part'
autoload :PartContainer, 'action_mailer/part_container'
autoload :Quoting, 'action_mailer/quoting'
autoload :TestCase, 'action_mailer/test_case'
autoload :TestHelper, 'action_mailer/test_helper'
autoload :Utils, 'action_mailer/utils'
end
module Text
autoload :Format, 'action_mailer/vendor/text_format'
end
module Net
autoload :SMTP, 'net/smtp'
end
autoload :MailHelper, 'action_mailer/mail_helper'
require 'action_mailer/vendor/tmail'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/test_case.rb | provider/vendor/rails/actionmailer/lib/action_mailer/test_case.rb | require 'active_support/test_case'
module ActionMailer
class NonInferrableMailerError < ::StandardError
def initialize(name)
super "Unable to determine the mailer to test from #{name}. " +
"You'll need to specify it using tests YourMailer in your " +
"test case definition"
end
end
class TestCase < ActiveSupport::TestCase
include Quoting, TestHelper
setup :initialize_test_deliveries
setup :set_expected_mail
class << self
def tests(mailer)
write_inheritable_attribute(:mailer_class, mailer)
end
def mailer_class
if mailer = read_inheritable_attribute(:mailer_class)
mailer
else
tests determine_default_mailer(name)
end
end
def determine_default_mailer(name)
name.sub(/Test$/, '').constantize
rescue NameError => e
raise NonInferrableMailerError.new(name)
end
end
protected
def initialize_test_deliveries
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
def set_expected_mail
@expected = TMail::Mail.new
@expected.set_content_type "text", "plain", { "charset" => charset }
@expected.mime_version = '1.0'
end
private
def charset
"utf-8"
end
def encode(subject)
quoted_printable(subject, charset)
end
def read_fixture(action)
IO.readlines(File.join(RAILS_ROOT, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/version.rb | provider/vendor/rails/actionmailer/lib/action_mailer/version.rb | module ActionMailer
module VERSION #:nodoc:
MAJOR = 2
MINOR = 3
TINY = 4
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/utils.rb | provider/vendor/rails/actionmailer/lib/action_mailer/utils.rb | module ActionMailer
module Utils #:nodoc:
def normalize_new_lines(text)
text.to_s.gsub(/\r\n?/, "\n")
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/part_container.rb | provider/vendor/rails/actionmailer/lib/action_mailer/part_container.rb | module ActionMailer
# Accessors and helpers that ActionMailer::Base and ActionMailer::Part have
# in common. Using these helpers you can easily add subparts or attachments
# to your message:
#
# def my_mail_message(...)
# ...
# part "text/plain" do |p|
# p.body "hello, world"
# p.transfer_encoding "base64"
# end
#
# attachment "image/jpg" do |a|
# a.body = File.read("hello.jpg")
# a.filename = "hello.jpg"
# end
# end
module PartContainer
# The list of subparts of this container
attr_reader :parts
# Add a part to a multipart message, with the given content-type. The
# part itself is yielded to the block so that other properties (charset,
# body, headers, etc.) can be set on it.
def part(params)
params = {:content_type => params} if String === params
part = Part.new(params)
yield part if block_given?
@parts << part
end
# Add an attachment to a multipart message. This is simply a part with the
# content-disposition set to "attachment".
def attachment(params, &block)
params = { :content_type => params } if String === params
params = { :disposition => "attachment",
:transfer_encoding => "base64" }.merge(params)
part(params, &block)
end
private
def parse_content_type(defaults=nil)
if content_type.blank?
return defaults ?
[ defaults.content_type, { 'charset' => defaults.charset } ] :
[ nil, {} ]
end
ctype, *attrs = content_type.split(/;\s*/)
attrs = attrs.inject({}) { |h,s| k,v = s.split(/=/, 2); h[k] = v; h }
[ctype, {"charset" => charset || defaults && defaults.charset}.merge(attrs)]
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/helpers.rb | provider/vendor/rails/actionmailer/lib/action_mailer/helpers.rb | require 'active_support/dependencies'
module ActionMailer
module Helpers #:nodoc:
def self.included(base) #:nodoc:
# Initialize the base module to aggregate its helpers.
base.class_inheritable_accessor :master_helper_module
base.master_helper_module = Module.new
# Extend base with class methods to declare helpers.
base.extend(ClassMethods)
base.class_eval do
# Wrap inherited to create a new master helper module for subclasses.
class << self
alias_method_chain :inherited, :helper
end
# Wrap initialize_template_class to extend new template class
# instances with the master helper module.
alias_method_chain :initialize_template_class, :helper
end
end
module ClassMethods
# Makes all the (instance) methods in the helper module available to templates rendered through this controller.
# See ActionView::Helpers (link:classes/ActionView/Helpers.html) for more about making your own helper modules
# available to the templates.
def add_template_helper(helper_module) #:nodoc:
master_helper_module.module_eval "include #{helper_module}"
end
# Declare a helper:
# helper :foo
# requires 'foo_helper' and includes FooHelper in the template class.
# helper FooHelper
# includes FooHelper in the template class.
# helper { def foo() "#{bar} is the very best" end }
# evaluates the block in the template class, adding method +foo+.
# helper(:three, BlindHelper) { def mice() 'mice' end }
# does all three.
def helper(*args, &block)
args.flatten.each do |arg|
case arg
when Module
add_template_helper(arg)
when String, Symbol
file_name = arg.to_s.underscore + '_helper'
class_name = file_name.camelize
begin
require_dependency(file_name)
rescue LoadError => load_error
requiree = / -- (.*?)(\.rb)?$/.match(load_error.message).to_a[1]
msg = (requiree == file_name) ? "Missing helper file helpers/#{file_name}.rb" : "Can't load file: #{requiree}"
raise LoadError.new(msg).copy_blame!(load_error)
end
add_template_helper(class_name.constantize)
else
raise ArgumentError, 'helper expects String, Symbol, or Module argument'
end
end
# Evaluate block in template class if given.
master_helper_module.module_eval(&block) if block_given?
end
# Declare a controller method as a helper. For example,
# helper_method :link_to
# def link_to(name, options) ... end
# makes the link_to controller method available in the view.
def helper_method(*methods)
methods.flatten.each do |method|
master_helper_module.module_eval <<-end_eval
def #{method}(*args, &block)
controller.__send__(%(#{method}), *args, &block)
end
end_eval
end
end
# Declare a controller attribute as a helper. For example,
# helper_attr :name
# attr_accessor :name
# makes the name and name= controller methods available in the view.
# The is a convenience wrapper for helper_method.
def helper_attr(*attrs)
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
end
private
def inherited_with_helper(child)
inherited_without_helper(child)
begin
child.master_helper_module = Module.new
child.master_helper_module.__send__(:include, master_helper_module)
child.helper child.name.to_s.underscore
rescue MissingSourceFile => e
raise unless e.is_missing?("helpers/#{child.name.to_s.underscore}_helper")
end
end
end
private
# Extend the template class instance with our controller's helper module.
def initialize_template_class_with_helper(assigns)
returning(template = initialize_template_class_without_helper(assigns)) do
template.extend self.class.master_helper_module
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/base.rb | provider/vendor/rails/actionmailer/lib/action_mailer/base.rb | module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
#
#
# = Mailer Models
#
# To use Action Mailer, you need to create a mailer model.
#
# $ script/generate mailer Notifier
#
# The generated model inherits from ActionMailer::Base. Emails are defined by creating methods within the model which are then
# used to set variables to be used in the mail template, to change options on the mail, or
# to add attachments.
#
# Examples:
#
# class Notifier < ActionMailer::Base
# def signup_notification(recipient)
# recipients recipient.email_address_with_name
# bcc ["bcc@example.com", "Order Watcher <watcher@example.com>"]
# from "system@example.com"
# subject "New account information"
# body :account => recipient
# end
# end
#
# Mailer methods have the following configuration methods available.
#
# * <tt>recipients</tt> - Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the <tt>To:</tt> header.
# * <tt>subject</tt> - The subject of your email. Sets the <tt>Subject:</tt> header.
# * <tt>from</tt> - Who the email you are sending is from. Sets the <tt>From:</tt> header.
# * <tt>cc</tt> - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the <tt>Cc:</tt> header.
# * <tt>bcc</tt> - Takes one or more email addresses. These addresses will receive a blind carbon copy of your email. Sets the <tt>Bcc:</tt> header.
# * <tt>reply_to</tt> - Takes one or more email addresses. These addresses will be listed as the default recipients when replying to your email. Sets the <tt>Reply-To:</tt> header.
# * <tt>sent_on</tt> - The date on which the message was sent. If not set, the header wil be set by the delivery agent.
# * <tt>content_type</tt> - Specify the content type of the message. Defaults to <tt>text/plain</tt>.
# * <tt>headers</tt> - Specify additional headers to be set for the message, e.g. <tt>headers 'X-Mail-Count' => 107370</tt>.
#
# When a <tt>headers 'return-path'</tt> is specified, that value will be used as the 'envelope from'
# address. Setting this is useful when you want delivery notifications sent to a different address than
# the one in <tt>from</tt>.
#
# The <tt>body</tt> method has special behavior. It takes a hash which generates an instance variable
# named after each key in the hash containing the value that that key points to.
#
# So, for example, <tt>body :account => recipient</tt> would result
# in an instance variable <tt>@account</tt> with the value of <tt>recipient</tt> being accessible in the
# view.
#
#
# = Mailer views
#
# Like Action Controller, each mailer class has a corresponding view directory
# in which each method of the class looks for a template with its name.
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same name as the method
# in your mailer model. For example, in the mailer defined above, the template at
# <tt>app/views/notifier/signup_notification.erb</tt> would be used to generate the email.
#
# Variables defined in the model are accessible as instance variables in the view.
#
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
#
# Hi <%= @account.name %>,
# Thanks for joining our service! Please check back often.
#
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
# <%= truncate(note.body, 25) %>
#
#
# = Generating URLs
#
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes.
# Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request,
# so you'll need to provide all of the details needed to generate a URL.
#
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
#
# <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
#
# When using named routes you only need to supply the <tt>:host</tt>:
#
# <%= users_url(:host => "example.com") %>
#
# You will want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't make sense to
# generate relative URLs in email messages.
#
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt> option in
# the <tt>ActionMailer::Base.default_url_options</tt> hash as follows:
#
# ActionMailer::Base.default_url_options[:host] = "example.com"
#
# This can also be set as a configuration option in <tt>config/environment.rb</tt>:
#
# config.action_mailer.default_url_options = { :host => "example.com" }
#
# If you do decide to set a default <tt>:host</tt> for your mailers you will want to use the
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are generated because
# the <tt>url_for</tt> view helper will, by default, generate relative URLs when a <tt>:host</tt> option isn't
# explicitly provided.
#
# = Sending mail
#
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
# Notifier.deliver_signup_notification(david) # sends the email
# mail = Notifier.create_signup_notification(david) # => a tmail object
# Notifier.deliver(mail)
#
# You never instantiate your mailer class. Rather, your delivery instance
# methods are automatically wrapped in class methods that start with the word
# <tt>deliver_</tt> followed by the name of the mailer method that you would
# like to deliver. The <tt>signup_notification</tt> method defined above is
# delivered by invoking <tt>Notifier.deliver_signup_notification</tt>.
#
#
# = HTML email
#
# To send mail as HTML, make sure your view (the <tt>.erb</tt> file) generates HTML and
# set the content type to html.
#
# class MyMailer < ActionMailer::Base
# def signup_notification(recipient)
# recipients recipient.email_address_with_name
# subject "New account information"
# from "system@example.com"
# body :account => recipient
# content_type "text/html"
# end
# end
#
#
# = Multipart email
#
# You can explicitly specify multipart messages:
#
# class ApplicationMailer < ActionMailer::Base
# def signup_notification(recipient)
# recipients recipient.email_address_with_name
# subject "New account information"
# from "system@example.com"
# content_type "multipart/alternative"
#
# part :content_type => "text/html",
# :body => render_message("signup-as-html", :account => recipient)
#
# part "text/plain" do |p|
# p.body = render_message("signup-as-plain", :account => recipient)
# p.transfer_encoding = "base64"
# end
# end
# end
#
# Multipart messages can also be used implicitly because Action Mailer will automatically
# detect and use multipart templates, where each template is named after the name of the action, followed
# by the content type. Each such detected template will be added as separate part to the message.
#
# For example, if the following templates existed:
# * signup_notification.text.plain.erb
# * signup_notification.text.html.erb
# * signup_notification.text.xml.builder
# * signup_notification.text.x-yaml.erb
#
# Each would be rendered and added as a separate part to the message,
# with the corresponding content type. The content type for the entire
# message is automatically set to <tt>multipart/alternative</tt>, which indicates
# that the email contains multiple different representations of the same email
# body. The same body hash is passed to each template.
#
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
# This means that you'll have to manually add each part to the email and set the content type of the email
# to <tt>multipart/alternative</tt>.
#
# = Attachments
#
# Attachments can be added by using the +attachment+ method.
#
# Example:
#
# class ApplicationMailer < ActionMailer::Base
# # attachments
# def signup_notification(recipient)
# recipients recipient.email_address_with_name
# subject "New account information"
# from "system@example.com"
#
# attachment :content_type => "image/jpeg",
# :body => File.read("an-image.jpg")
#
# attachment "application/pdf" do |a|
# a.body = generate_your_pdf_here()
# end
# end
# end
#
#
# = Configuration options
#
# These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>template_root</tt> - Determines the base from which template references will be made.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here.
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server and starts to use it.
# It works only on Ruby >= 1.8.7 and Ruby >= 1.9. Default is true.
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>.
#
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.
#
# * <tt>perform_deliveries</tt> - Determines whether <tt>deliver_*</tt> methods are actually carried out. By default they are,
# but this can be turned off to help functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
# for unit and functional testing.
#
# * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
# pick a different charset from inside a method with +charset+.
#
# * <tt>default_content_type</tt> - The default content type used for the main part of the message. Defaults to "text/plain". You
# can also pick a different content type from inside a method with +content_type+.
#
# * <tt>default_mime_version</tt> - The default mime version used for the message. Defaults to <tt>1.0</tt>. You
# can also pick a different value from inside a method with +mime_version+.
#
# * <tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assembled from templates
# which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
# <tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
# and appear last in the mime encoded message. You can also pick a different order from inside a method with
# +implicit_parts_order+.
class Base
include AdvAttrAccessor, PartContainer, Quoting, Utils
if Object.const_defined?(:ActionController)
include ActionController::UrlWriter
include ActionController::Layout
end
private_class_method :new #:nodoc:
class_inheritable_accessor :view_paths
self.view_paths = []
cattr_accessor :logger
@@smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'localhost.localdomain',
:user_name => nil,
:password => nil,
:authentication => nil,
:enable_starttls_auto => true,
}
cattr_accessor :smtp_settings
@@sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
cattr_accessor :sendmail_settings
@@raise_delivery_errors = true
cattr_accessor :raise_delivery_errors
superclass_delegating_accessor :delivery_method
self.delivery_method = :smtp
@@perform_deliveries = true
cattr_accessor :perform_deliveries
@@deliveries = []
cattr_accessor :deliveries
@@default_charset = "utf-8"
cattr_accessor :default_charset
@@default_content_type = "text/plain"
cattr_accessor :default_content_type
@@default_mime_version = "1.0"
cattr_accessor :default_mime_version
@@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
cattr_accessor :default_implicit_parts_order
cattr_reader :protected_instance_variables
@@protected_instance_variables = %w(@body)
# Specify the BCC addresses for the message
adv_attr_accessor :bcc
# Define the body of the message. This is either a Hash (in which case it
# specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
adv_attr_accessor :body
# Specify the CC addresses for the message.
adv_attr_accessor :cc
# Specify the charset to use for the message. This defaults to the
# +default_charset+ specified for ActionMailer::Base.
adv_attr_accessor :charset
# Specify the content type for the message. This defaults to <tt>text/plain</tt>
# in most cases, but can be automatically set in some situations.
adv_attr_accessor :content_type
# Specify the from address for the message.
adv_attr_accessor :from
# Specify the address (if different than the "from" address) to direct
# replies to this message.
adv_attr_accessor :reply_to
# Specify additional headers to be added to the message.
adv_attr_accessor :headers
# Specify the order in which parts should be sorted, based on content-type.
# This defaults to the value for the +default_implicit_parts_order+.
adv_attr_accessor :implicit_parts_order
# Defaults to "1.0", but may be explicitly given if needed.
adv_attr_accessor :mime_version
# The recipient addresses for the message, either as a string (for a single
# address) or an array (for multiple addresses).
adv_attr_accessor :recipients
# The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
adv_attr_accessor :sent_on
# Specify the subject of the message.
adv_attr_accessor :subject
# Specify the template name to use for current message. This is the "base"
# template name, without the extension or directory, and may be used to
# have multiple mailer methods share the same template.
adv_attr_accessor :template
# Override the mailer name, which defaults to an inflected version of the
# mailer's class name. If you want to use a template in a non-standard
# location, you can use this to specify that location.
def mailer_name(value = nil)
if value
self.mailer_name = value
else
self.class.mailer_name
end
end
def mailer_name=(value)
self.class.mailer_name = value
end
# The mail object instance referenced by this mailer.
attr_reader :mail
attr_reader :template_name, :default_template_name, :action_name
class << self
attr_writer :mailer_name
def mailer_name
@mailer_name ||= name.underscore
end
# for ActionView compatibility
alias_method :controller_name, :mailer_name
alias_method :controller_path, :mailer_name
def respond_to?(method_symbol, include_private = false) #:nodoc:
matches_dynamic_method?(method_symbol) || super
end
def method_missing(method_symbol, *parameters) #:nodoc:
if match = matches_dynamic_method?(method_symbol)
case match[1]
when 'create' then new(match[2], *parameters).mail
when 'deliver' then new(match[2], *parameters).deliver!
when 'new' then nil
else super
end
else
super
end
end
# Receives a raw email, parses it into an email object, decodes it,
# instantiates a new mailer, and passes the email object to the mailer
# object's +receive+ method. If you want your mailer to be able to
# process incoming messages, you'll need to implement a +receive+
# method that accepts the email object as a parameter:
#
# class MyMailer < ActionMailer::Base
# def receive(mail)
# ...
# end
# end
def receive(raw_email)
logger.info "Received mail:\n #{raw_email}" unless logger.nil?
mail = TMail::Mail.parse(raw_email)
mail.base64_decode
new.receive(mail)
end
# Deliver the given mail object directly. This can be used to deliver
# a preconstructed mail object, like:
#
# email = MyMailer.create_some_mail(parameters)
# email.set_some_obscure_header "frobnicate"
# MyMailer.deliver(email)
def deliver(mail)
new.deliver!(mail)
end
def template_root
self.view_paths && self.view_paths.first
end
def template_root=(root)
self.view_paths = ActionView::Base.process_view_paths(root)
end
private
def matches_dynamic_method?(method_name) #:nodoc:
method_name = method_name.to_s
/^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
end
end
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
# remain uninitialized (useful when you only need to invoke the "receive"
# method, for instance).
def initialize(method_name=nil, *parameters) #:nodoc:
create!(method_name, *parameters) if method_name
end
# Initialize the mailer via the given +method_name+. The body will be
# rendered and a new TMail::Mail object created.
def create!(method_name, *parameters) #:nodoc:
initialize_defaults(method_name)
__send__(method_name, *parameters)
# If an explicit, textual body has not been set, we check assumptions.
unless String === @body
# First, we look to see if there are any likely templates that match,
# which include the content-type in their file name (i.e.,
# "the_template_file.text.html.erb", etc.). Only do this if parts
# have not already been specified manually.
if @parts.empty?
Dir.glob("#{template_path}/#{@template}.*").each do |path|
template = template_root["#{mailer_name}/#{File.basename(path)}"]
# Skip unless template has a multipart format
next unless template && template.multipart?
@parts << Part.new(
:content_type => template.content_type,
:disposition => "inline",
:charset => charset,
:body => render_message(template, @body)
)
end
unless @parts.empty?
@content_type = "multipart/alternative" if @content_type !~ /^multipart/
@parts = sort_parts(@parts, @implicit_parts_order)
end
end
# Then, if there were such templates, we check to see if we ought to
# also render a "normal" template (without the content type). If a
# normal template exists (or if there were no implicit parts) we render
# it.
template_exists = @parts.empty?
template_exists ||= template_root["#{mailer_name}/#{@template}"]
@body = render_message(@template, @body) if template_exists
# Finally, if there are other message parts and a textual body exists,
# we shift it onto the front of the parts and set the body to nil (so
# that create_mail doesn't try to render it in addition to the parts).
if !@parts.empty? && String === @body
@parts.unshift Part.new(:charset => charset, :body => @body)
@body = nil
end
end
# If this is a multipart e-mail add the mime_version if it is not
# already set.
@mime_version ||= "1.0" if !@parts.empty?
# build the mail object itself
@mail = create_mail
end
# Delivers a TMail::Mail object. By default, it delivers the cached mail
# object (from the <tt>create!</tt> method). If no cached mail object exists, and
# no alternate has been given as the parameter, this will fail.
def deliver!(mail = @mail)
raise "no mail object available for delivery!" unless mail
unless logger.nil?
logger.info "Sent mail to #{Array(recipients).join(', ')}"
logger.debug "\n#{mail.encoded}"
end
begin
__send__("perform_delivery_#{delivery_method}", mail) if perform_deliveries
rescue Exception => e # Net::SMTP errors or sendmail pipe errors
raise e if raise_delivery_errors
end
return mail
end
private
# Set up the default values for the various instance variables of this
# mailer. Subclasses may override this method to provide different
# defaults.
def initialize_defaults(method_name)
@charset ||= @@default_charset.dup
@content_type ||= @@default_content_type.dup
@implicit_parts_order ||= @@default_implicit_parts_order.dup
@template ||= method_name
@default_template_name = @action_name = @template
@mailer_name ||= self.class.name.underscore
@parts ||= []
@headers ||= {}
@body ||= {}
@mime_version = @@default_mime_version.dup if @@default_mime_version
@sent_on ||= Time.now
end
def render_message(method_name, body)
if method_name.respond_to?(:content_type)
@current_template_content_type = method_name.content_type
end
render :file => method_name, :body => body
ensure
@current_template_content_type = nil
end
def render(opts)
body = opts.delete(:body)
if opts[:file] && (opts[:file] !~ /\// && !opts[:file].respond_to?(:render))
opts[:file] = "#{mailer_name}/#{opts[:file]}"
end
begin
old_template, @template = @template, initialize_template_class(body)
layout = respond_to?(:pick_layout, true) ? pick_layout(opts) : false
@template.render(opts.merge(:layout => layout))
ensure
@template = old_template
end
end
def default_template_format
if @current_template_content_type
Mime::Type.lookup(@current_template_content_type).to_sym
else
:html
end
end
def candidate_for_layout?(options)
!self.view_paths.find_template(default_template_name, default_template_format).exempt_from_layout?
rescue ActionView::MissingTemplate
return true
end
def template_root
self.class.template_root
end
def template_root=(root)
self.class.template_root = root
end
def template_path
"#{template_root}/#{mailer_name}"
end
def initialize_template_class(assigns)
template = ActionView::Base.new(self.class.view_paths, assigns, self)
template.template_format = default_template_format
template
end
def sort_parts(parts, order = [])
order = order.collect { |s| s.downcase }
parts = parts.sort do |a, b|
a_ct = a.content_type.downcase
b_ct = b.content_type.downcase
a_in = order.include? a_ct
b_in = order.include? b_ct
s = case
when a_in && b_in
order.index(a_ct) <=> order.index(b_ct)
when a_in
-1
when b_in
1
else
a_ct <=> b_ct
end
# reverse the ordering because parts that come last are displayed
# first in mail clients
(s * -1)
end
parts
end
def create_mail
m = TMail::Mail.new
m.subject, = quote_any_if_necessary(charset, subject)
m.to, m.from = quote_any_address_if_necessary(charset, recipients, from)
m.bcc = quote_address_if_necessary(bcc, charset) unless bcc.nil?
m.cc = quote_address_if_necessary(cc, charset) unless cc.nil?
m.reply_to = quote_address_if_necessary(reply_to, charset) unless reply_to.nil?
m.mime_version = mime_version unless mime_version.nil?
m.date = sent_on.to_time rescue sent_on if sent_on
headers.each { |k, v| m[k] = v }
real_content_type, ctype_attrs = parse_content_type
if @parts.empty?
m.set_content_type(real_content_type, nil, ctype_attrs)
m.body = normalize_new_lines(body)
else
if String === body
part = TMail::Mail.new
part.body = normalize_new_lines(body)
part.set_content_type(real_content_type, nil, ctype_attrs)
part.set_content_disposition "inline"
m.parts << part
end
@parts.each do |p|
part = (TMail::Mail === p ? p : p.to_mail(self))
m.parts << part
end
if real_content_type =~ /multipart/
ctype_attrs.delete "charset"
m.set_content_type(real_content_type, nil, ctype_attrs)
end
end
@mail = m
end
def perform_delivery_smtp(mail)
destinations = mail.destinations
mail.ready_to_send
sender = (mail['return-path'] && mail['return-path'].spec) || mail['from']
smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
smtp.enable_starttls_auto if smtp_settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
smtp_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, sender, destinations)
end
end
def perform_delivery_sendmail(mail)
sendmail_args = sendmail_settings[:arguments]
sendmail_args += " -f \"#{mail['return-path']}\"" if mail['return-path']
IO.popen("#{sendmail_settings[:location]} #{sendmail_args}","w+") do |sm|
sm.print(mail.encoded.gsub(/\r/, ''))
sm.flush
end
end
def perform_delivery_test(mail)
deliveries << mail
end
end
Base.class_eval do
include Helpers
helper MailHelper
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/test_helper.rb | provider/vendor/rails/actionmailer/lib/action_mailer/test_helper.rb | module ActionMailer
module TestHelper
# Asserts that the number of emails sent matches the given number.
#
# def test_emails
# assert_emails 0
# ContactMailer.deliver_contact
# assert_emails 1
# ContactMailer.deliver_contact
# assert_emails 2
# end
#
# If a block is passed, that block should cause the specified number of emails to be sent.
#
# def test_emails_again
# assert_emails 1 do
# ContactMailer.deliver_contact
# end
#
# assert_emails 2 do
# ContactMailer.deliver_contact
# ContactMailer.deliver_contact
# end
# end
def assert_emails(number)
if block_given?
original_count = ActionMailer::Base.deliveries.size
yield
new_count = ActionMailer::Base.deliveries.size
assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
else
assert_equal number, ActionMailer::Base.deliveries.size
end
end
# Assert that no emails have been sent.
#
# def test_emails
# assert_no_emails
# ContactMailer.deliver_contact
# assert_emails 1
# end
#
# If a block is passed, that block should not cause any emails to be sent.
#
# def test_emails_again
# assert_no_emails do
# # No emails should be sent from this block
# end
# end
#
# Note: This assertion is simply a shortcut for:
#
# assert_emails 0
def assert_no_emails(&block)
assert_emails 0, &block
end
end
end
# TODO: Deprecate this
module Test
module Unit
class TestCase
include ActionMailer::TestHelper
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/quoting.rb | provider/vendor/rails/actionmailer/lib/action_mailer/quoting.rb | module ActionMailer
module Quoting #:nodoc:
# Convert the given text into quoted printable format, with an instruction
# that the text be eventually interpreted in the given charset.
def quoted_printable(text, charset)
text = text.gsub( /[^a-z ]/i ) { quoted_printable_encode($&) }.
gsub( / /, "_" )
"=?#{charset}?Q?#{text}?="
end
# Convert the given character to quoted printable format, taking into
# account multi-byte characters (if executing with $KCODE="u", for instance)
def quoted_printable_encode(character)
result = ""
character.each_byte { |b| result << "=%02X" % b }
result
end
# A quick-and-dirty regexp for determining whether a string contains any
# characters that need escaping.
if !defined?(CHARS_NEEDING_QUOTING)
CHARS_NEEDING_QUOTING = /[\000-\011\013\014\016-\037\177-\377]/
end
# Quote the given text if it contains any "illegal" characters
def quote_if_necessary(text, charset)
text = text.dup.force_encoding(Encoding::ASCII_8BIT) if text.respond_to?(:force_encoding)
(text =~ CHARS_NEEDING_QUOTING) ?
quoted_printable(text, charset) :
text
end
# Quote any of the given strings if they contain any "illegal" characters
def quote_any_if_necessary(charset, *args)
args.map { |v| quote_if_necessary(v, charset) }
end
# Quote the given address if it needs to be. The address may be a
# regular email address, or it can be a phrase followed by an address in
# brackets. The phrase is the only part that will be quoted, and only if
# it needs to be. This allows extended characters to be used in the
# "to", "from", "cc", "bcc" and "reply-to" headers.
def quote_address_if_necessary(address, charset)
if Array === address
address.map { |a| quote_address_if_necessary(a, charset) }
elsif address =~ /^(\S.*)\s+(<.*>)$/
address = $2
phrase = quote_if_necessary($1.gsub(/^['"](.*)['"]$/, '\1'), charset)
"\"#{phrase}\" #{address}"
else
address
end
end
# Quote any of the given addresses, if they need to be.
def quote_any_address_if_necessary(charset, *args)
args.map { |v| quote_address_if_necessary(v, charset) }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb | provider/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb | module ActionMailer
module AdvAttrAccessor #:nodoc:
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods #:nodoc:
def adv_attr_accessor(*names)
names.each do |name|
ivar = "@#{name}"
define_method("#{name}=") do |value|
instance_variable_set(ivar, value)
end
define_method(name) do |*parameters|
raise ArgumentError, "expected 0 or 1 parameters" unless parameters.length <= 1
if parameters.empty?
if instance_variable_names.include?(ivar)
instance_variable_get(ivar)
end
else
instance_variable_set(ivar, parameters.first)
end
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/mail_helper.rb | provider/vendor/rails/actionmailer/lib/action_mailer/mail_helper.rb | module MailHelper
# Uses Text::Format to take the text and format it, indented two spaces for
# each line, and wrapped at 72 columns.
def block_format(text)
formatted = text.split(/\n\r\n/).collect { |paragraph|
Text::Format.new(
:columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
).format
}.join("\n")
# Make list points stand on their own line
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
formatted
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/part.rb | provider/vendor/rails/actionmailer/lib/action_mailer/part.rb | module ActionMailer
# Represents a subpart of an email message. It shares many similar
# attributes of ActionMailer::Base. Although you can create parts manually
# and add them to the +parts+ list of the mailer, it is easier
# to use the helper methods in ActionMailer::PartContainer.
class Part
include AdvAttrAccessor, PartContainer, Utils
# Represents the body of the part, as a string. This should not be a
# Hash (like ActionMailer::Base), but if you want a template to be rendered
# into the body of a subpart you can do it with the mailer's +render+ method
# and assign the result here.
adv_attr_accessor :body
# Specify the charset for this subpart. By default, it will be the charset
# of the containing part or mailer.
adv_attr_accessor :charset
# The content disposition of this part, typically either "inline" or
# "attachment".
adv_attr_accessor :content_disposition
# The content type of the part.
adv_attr_accessor :content_type
# The filename to use for this subpart (usually for attachments).
adv_attr_accessor :filename
# Accessor for specifying additional headers to include with this part.
adv_attr_accessor :headers
# The transfer encoding to use for this subpart, like "base64" or
# "quoted-printable".
adv_attr_accessor :transfer_encoding
# Create a new part from the given +params+ hash. The valid params keys
# correspond to the accessors.
def initialize(params)
@content_type = params[:content_type]
@content_disposition = params[:disposition] || "inline"
@charset = params[:charset]
@body = params[:body]
@filename = params[:filename]
@transfer_encoding = params[:transfer_encoding] || "quoted-printable"
@headers = params[:headers] || {}
@parts = []
end
# Convert the part to a mail object which can be included in the parts
# list of another mail object.
def to_mail(defaults)
part = TMail::Mail.new
real_content_type, ctype_attrs = parse_content_type(defaults)
if @parts.empty?
part.content_transfer_encoding = transfer_encoding || "quoted-printable"
case (transfer_encoding || "").downcase
when "base64" then
part.body = TMail::Base64.folding_encode(body)
when "quoted-printable"
part.body = [normalize_new_lines(body)].pack("M*")
else
part.body = body
end
# Always set the content_type after setting the body and or parts!
# Also don't set filename and name when there is none (like in
# non-attachment parts)
if content_disposition == "attachment"
ctype_attrs.delete "charset"
part.set_content_type(real_content_type, nil,
squish("name" => filename).merge(ctype_attrs))
part.set_content_disposition(content_disposition,
squish("filename" => filename).merge(ctype_attrs))
else
part.set_content_type(real_content_type, nil, ctype_attrs)
part.set_content_disposition(content_disposition)
end
else
if String === body
@parts.unshift Part.new(:charset => charset, :body => @body, :content_type => 'text/plain')
@body = nil
end
@parts.each do |p|
prt = (TMail::Mail === p ? p : p.to_mail(defaults))
part.parts << prt
end
if real_content_type =~ /multipart/
ctype_attrs.delete 'charset'
part.set_content_type(real_content_type, nil, ctype_attrs)
end
end
headers.each { |k,v| part[k] = v }
part
end
private
def squish(values={})
values.delete_if { |k,v| v.nil? }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/text_format.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/text_format.rb | # Prefer gems to the bundled libs.
require 'rubygems'
begin
gem 'text-format', '>= 0.6.3'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/text-format-0.6.3"
end
require 'text/format'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail.rb | # Prefer gems to the bundled libs.
require 'rubygems'
begin
gem 'tmail', '~> 1.2.3'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/tmail-1.2.3"
end
module TMail
end
require 'tmail'
silence_warnings do
TMail::Encoder.const_set("MAX_LINE_LEN", 200)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb | #--
# Text::Format for Ruby
# Version 0.63
#
# Copyright (c) 2002 - 2003 Austin Ziegler
#
# $Id: format.rb,v 1.1.1.1 2004/10/14 11:59:57 webster132 Exp $
#
# ==========================================================================
# Revision History ::
# YYYY.MM.DD Change ID Developer
# Description
# --------------------------------------------------------------------------
# 2002.10.18 Austin Ziegler
# Fixed a minor problem with tabs not being counted. Changed
# abbreviations from Hash to Array to better suit Ruby's
# capabilities. Fixed problems with the way that Array arguments
# are handled in calls to the major object types, excepting in
# Text::Format#expand and Text::Format#unexpand (these will
# probably need to be fixed).
# 2002.10.30 Austin Ziegler
# Fixed the ordering of the <=> for binary tests. Fixed
# Text::Format#expand and Text::Format#unexpand to handle array
# arguments better.
# 2003.01.24 Austin Ziegler
# Fixed a problem with Text::Format::RIGHT_FILL handling where a
# single word is larger than #columns. Removed Comparable
# capabilities (<=> doesn't make sense; == does). Added Symbol
# equivalents for the Hash initialization. Hash initialization has
# been modified so that values are set as follows (Symbols are
# highest priority; strings are middle; defaults are lowest):
# @columns = arg[:columns] || arg['columns'] || @columns
# Added #hard_margins, #split_rules, #hyphenator, and #split_words.
# 2003.02.07 Austin Ziegler
# Fixed the installer for proper case-sensitive handling.
# 2003.03.28 Austin Ziegler
# Added the ability for a hyphenator to receive the formatter
# object. Fixed a bug for strings matching /\A\s*\Z/ failing
# entirely. Fixed a test case failing under 1.6.8.
# 2003.04.04 Austin Ziegler
# Handle the case of hyphenators returning nil for first/rest.
# 2003.09.17 Austin Ziegler
# Fixed a problem where #paragraphs(" ") was raising
# NoMethodError.
#
# ==========================================================================
#++
module Text #:nodoc:
# Text::Format for Ruby is copyright 2002 - 2005 by Austin Ziegler. It
# is available under Ruby's licence, the Perl Artistic licence, or the
# GNU GPL version 2 (or at your option, any later version). As a
# special exception, for use with official Rails (provided by the
# rubyonrails.org development team) and any project created with
# official Rails, the following alternative MIT-style licence may be
# used:
#
# == Text::Format Licence for Rails and Rails Applications
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# * The names of its contributors may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class Format
VERSION = '0.63'
# Local abbreviations. More can be added with Text::Format.abbreviations
ABBREV = [ 'Mr', 'Mrs', 'Ms', 'Jr', 'Sr' ]
# Formatting values
LEFT_ALIGN = 0
RIGHT_ALIGN = 1
RIGHT_FILL = 2
JUSTIFY = 3
# Word split modes (only applies when #hard_margins is true).
SPLIT_FIXED = 1
SPLIT_CONTINUATION = 2
SPLIT_HYPHENATION = 4
SPLIT_CONTINUATION_FIXED = SPLIT_CONTINUATION | SPLIT_FIXED
SPLIT_HYPHENATION_FIXED = SPLIT_HYPHENATION | SPLIT_FIXED
SPLIT_HYPHENATION_CONTINUATION = SPLIT_HYPHENATION | SPLIT_CONTINUATION
SPLIT_ALL = SPLIT_HYPHENATION | SPLIT_CONTINUATION | SPLIT_FIXED
# Words forcibly split by Text::Format will be stored as split words.
# This class represents a word forcibly split.
class SplitWord
# The word that was split.
attr_reader :word
# The first part of the word that was split.
attr_reader :first
# The remainder of the word that was split.
attr_reader :rest
def initialize(word, first, rest) #:nodoc:
@word = word
@first = first
@rest = rest
end
end
private
LEQ_RE = /[.?!]['"]?$/
def brk_re(i) #:nodoc:
%r/((?:\S+\s+){#{i}})(.+)/
end
def posint(p) #:nodoc:
p.to_i.abs
end
public
# Compares two Text::Format objects. All settings of the objects are
# compared *except* #hyphenator. Generated results (e.g., #split_words)
# are not compared, either.
def ==(o)
(@text == o.text) &&
(@columns == o.columns) &&
(@left_margin == o.left_margin) &&
(@right_margin == o.right_margin) &&
(@hard_margins == o.hard_margins) &&
(@split_rules == o.split_rules) &&
(@first_indent == o.first_indent) &&
(@body_indent == o.body_indent) &&
(@tag_text == o.tag_text) &&
(@tabstop == o.tabstop) &&
(@format_style == o.format_style) &&
(@extra_space == o.extra_space) &&
(@tag_paragraph == o.tag_paragraph) &&
(@nobreak == o.nobreak) &&
(@abbreviations == o.abbreviations) &&
(@nobreak_regex == o.nobreak_regex)
end
# The text to be manipulated. Note that value is optional, but if the
# formatting functions are called without values, this text is what will
# be formatted.
#
# *Default*:: <tt>[]</tt>
# <b>Used in</b>:: All methods
attr_accessor :text
# The total width of the format area. The margins, indentation, and text
# are formatted into this space.
#
# COLUMNS
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin indent text is formatted into here right margin
#
# *Default*:: <tt>72</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
attr_reader :columns
# The total width of the format area. The margins, indentation, and text
# are formatted into this space. The value provided is silently
# converted to a positive integer.
#
# COLUMNS
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin indent text is formatted into here right margin
#
# *Default*:: <tt>72</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
def columns=(c)
@columns = posint(c)
end
# The number of spaces used for the left margin.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# LEFT MARGIN indent text is formatted into here right margin
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
attr_reader :left_margin
# The number of spaces used for the left margin. The value provided is
# silently converted to a positive integer value.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# LEFT MARGIN indent text is formatted into here right margin
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
def left_margin=(left)
@left_margin = posint(left)
end
# The number of spaces used for the right margin.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin indent text is formatted into here RIGHT MARGIN
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
attr_reader :right_margin
# The number of spaces used for the right margin. The value provided is
# silently converted to a positive integer value.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin indent text is formatted into here RIGHT MARGIN
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
# <tt>#center</tt>
def right_margin=(r)
@right_margin = posint(r)
end
# The number of spaces to indent the first line of a paragraph.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin INDENT text is formatted into here right margin
#
# *Default*:: <tt>4</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_reader :first_indent
# The number of spaces to indent the first line of a paragraph. The
# value provided is silently converted to a positive integer value.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin INDENT text is formatted into here right margin
#
# *Default*:: <tt>4</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def first_indent=(f)
@first_indent = posint(f)
end
# The number of spaces to indent all lines after the first line of a
# paragraph.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin INDENT text is formatted into here right margin
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_reader :body_indent
# The number of spaces to indent all lines after the first line of
# a paragraph. The value provided is silently converted to a
# positive integer value.
#
# columns
# <-------------------------------------------------------------->
# <-----------><------><---------------------------><------------>
# left margin INDENT text is formatted into here right margin
#
# *Default*:: <tt>0</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def body_indent=(b)
@body_indent = posint(b)
end
# Normally, words larger than the format area will be placed on a line
# by themselves. Setting this to +true+ will force words larger than the
# format area to be split into one or more "words" each at most the size
# of the format area. The first line and the original word will be
# placed into <tt>#split_words</tt>. Note that this will cause the
# output to look *similar* to a #format_style of JUSTIFY. (Lines will be
# filled as much as possible.)
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :hard_margins
# An array of words split during formatting if #hard_margins is set to
# +true+.
# #split_words << Text::Format::SplitWord.new(word, first, rest)
attr_reader :split_words
# The object responsible for hyphenating. It must respond to
# #hyphenate_to(word, size) or #hyphenate_to(word, size, formatter) and
# return an array of the word split into two parts; if there is a
# hyphenation mark to be applied, responsibility belongs to the
# hyphenator object. The size is the MAXIMUM size permitted, including
# any hyphenation marks. If the #hyphenate_to method has an arity of 3,
# the formatter will be provided to the method. This allows the
# hyphenator to make decisions about the hyphenation based on the
# formatting rules.
#
# *Default*:: +nil+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_reader :hyphenator
# The object responsible for hyphenating. It must respond to
# #hyphenate_to(word, size) and return an array of the word hyphenated
# into two parts. The size is the MAXIMUM size permitted, including any
# hyphenation marks.
#
# *Default*:: +nil+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def hyphenator=(h)
raise ArgumentError, "#{h.inspect} is not a valid hyphenator." unless h.respond_to?(:hyphenate_to)
arity = h.method(:hyphenate_to).arity
raise ArgumentError, "#{h.inspect} must have exactly two or three arguments." unless [2, 3].include?(arity)
@hyphenator = h
@hyphenator_arity = arity
end
# Specifies the split mode; used only when #hard_margins is set to
# +true+. Allowable values are:
# [+SPLIT_FIXED+] The word will be split at the number of
# characters needed, with no marking at all.
# repre
# senta
# ion
# [+SPLIT_CONTINUATION+] The word will be split at the number of
# characters needed, with a C-style continuation
# character. If a word is the only item on a
# line and it cannot be split into an
# appropriate size, SPLIT_FIXED will be used.
# repr\
# esen\
# tati\
# on
# [+SPLIT_HYPHENATION+] The word will be split according to the
# hyphenator specified in #hyphenator. If there
# is no #hyphenator specified, works like
# SPLIT_CONTINUATION. The example is using
# TeX::Hyphen. If a word is the only item on a
# line and it cannot be split into an
# appropriate size, SPLIT_CONTINUATION mode will
# be used.
# rep-
# re-
# sen-
# ta-
# tion
#
# *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_reader :split_rules
# Specifies the split mode; used only when #hard_margins is set to
# +true+. Allowable values are:
# [+SPLIT_FIXED+] The word will be split at the number of
# characters needed, with no marking at all.
# repre
# senta
# ion
# [+SPLIT_CONTINUATION+] The word will be split at the number of
# characters needed, with a C-style continuation
# character.
# repr\
# esen\
# tati\
# on
# [+SPLIT_HYPHENATION+] The word will be split according to the
# hyphenator specified in #hyphenator. If there
# is no #hyphenator specified, works like
# SPLIT_CONTINUATION. The example is using
# TeX::Hyphen as the #hyphenator.
# rep-
# re-
# sen-
# ta-
# tion
#
# These values can be bitwise ORed together (e.g., <tt>SPLIT_FIXED |
# SPLIT_CONTINUATION</tt>) to provide fallback split methods. In the
# example given, an attempt will be made to split the word using the
# rules of SPLIT_CONTINUATION; if there is not enough room, the word
# will be split with the rules of SPLIT_FIXED. These combinations are
# also available as the following values:
# * +SPLIT_CONTINUATION_FIXED+
# * +SPLIT_HYPHENATION_FIXED+
# * +SPLIT_HYPHENATION_CONTINUATION+
# * +SPLIT_ALL+
#
# *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def split_rules=(s)
raise ArgumentError, "Invalid value provided for split_rules." if ((s < SPLIT_FIXED) || (s > SPLIT_ALL))
@split_rules = s
end
# Indicates whether sentence terminators should be followed by a single
# space (+false+), or two spaces (+true+).
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :extra_space
# Defines the current abbreviations as an array. This is only used if
# extra_space is turned on.
#
# If one is abbreviating "President" as "Pres." (abbreviations =
# ["Pres"]), then the results of formatting will be as illustrated in
# the table below:
#
# extra_space | include? | !include?
# true | Pres. Lincoln | Pres. Lincoln
# false | Pres. Lincoln | Pres. Lincoln
#
# *Default*:: <tt>{}</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :abbreviations
# Indicates whether the formatting of paragraphs should be done with
# tagged paragraphs. Useful only with <tt>#tag_text</tt>.
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :tag_paragraph
# The array of text to be placed before each paragraph when
# <tt>#tag_paragraph</tt> is +true+. When <tt>#format()</tt> is called,
# only the first element of the array is used. When <tt>#paragraphs</tt>
# is called, then each entry in the array will be used once, with
# corresponding paragraphs. If the tag elements are exhausted before the
# text is exhausted, then the remaining paragraphs will not be tagged.
# Regardless of indentation settings, a blank line will be inserted
# between all paragraphs when <tt>#tag_paragraph</tt> is +true+.
#
# *Default*:: <tt>[]</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :tag_text
# Indicates whether or not the non-breaking space feature should be
# used.
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :nobreak
# A hash which holds the regular expressions on which spaces should not
# be broken. The hash is set up such that the key is the first word and
# the value is the second word.
#
# For example, if +nobreak_regex+ contains the following hash:
#
# { '^Mrs?\.$' => '\S+$', '^\S+$' => '^(?:S|J)r\.$'}
#
# Then "Mr. Jones", "Mrs. Jones", and "Jones Jr." would not be broken.
# If this simple matching algorithm indicates that there should not be a
# break at the current end of line, then a backtrack is done until there
# are two words on which line breaking is permitted. If two such words
# are not found, then the end of the line will be broken *regardless*.
# If there is a single word on the current line, then no backtrack is
# done and the word is stuck on the end.
#
# *Default*:: <tt>{}</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_accessor :nobreak_regex
# Indicates the number of spaces that a single tab represents.
#
# *Default*:: <tt>8</tt>
# <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
# <tt>#paragraphs</tt>
attr_reader :tabstop
# Indicates the number of spaces that a single tab represents.
#
# *Default*:: <tt>8</tt>
# <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
# <tt>#paragraphs</tt>
def tabstop=(t)
@tabstop = posint(t)
end
# Specifies the format style. Allowable values are:
# [+LEFT_ALIGN+] Left justified, ragged right.
# |A paragraph that is|
# |left aligned.|
# [+RIGHT_ALIGN+] Right justified, ragged left.
# |A paragraph that is|
# | right aligned.|
# [+RIGHT_FILL+] Left justified, right ragged, filled to width by
# spaces. (Essentially the same as +LEFT_ALIGN+ except
# that lines are padded on the right.)
# |A paragraph that is|
# |left aligned. |
# [+JUSTIFY+] Fully justified, words filled to width by spaces,
# except the last line.
# |A paragraph that|
# |is justified.|
#
# *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
attr_reader :format_style
# Specifies the format style. Allowable values are:
# [+LEFT_ALIGN+] Left justified, ragged right.
# |A paragraph that is|
# |left aligned.|
# [+RIGHT_ALIGN+] Right justified, ragged left.
# |A paragraph that is|
# | right aligned.|
# [+RIGHT_FILL+] Left justified, right ragged, filled to width by
# spaces. (Essentially the same as +LEFT_ALIGN+ except
# that lines are padded on the right.)
# |A paragraph that is|
# |left aligned. |
# [+JUSTIFY+] Fully justified, words filled to width by spaces.
# |A paragraph that|
# |is justified.|
#
# *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def format_style=(fs)
raise ArgumentError, "Invalid value provided for format_style." if ((fs < LEFT_ALIGN) || (fs > JUSTIFY))
@format_style = fs
end
# Indicates that the format style is left alignment.
#
# *Default*:: +true+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def left_align?
return @format_style == LEFT_ALIGN
end
# Indicates that the format style is right alignment.
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def right_align?
return @format_style == RIGHT_ALIGN
end
# Indicates that the format style is right fill.
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def right_fill?
return @format_style == RIGHT_FILL
end
# Indicates that the format style is full justification.
#
# *Default*:: +false+
# <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
def justify?
return @format_style == JUSTIFY
end
# The default implementation of #hyphenate_to implements
# SPLIT_CONTINUATION.
def hyphenate_to(word, size)
[word[0 .. (size - 2)] + "\\", word[(size - 1) .. -1]]
end
private
def __do_split_word(word, size) #:nodoc:
[word[0 .. (size - 1)], word[size .. -1]]
end
def __format(to_wrap) #:nodoc:
words = to_wrap.split(/\s+/).compact
words.shift if words[0].nil? or words[0].empty?
to_wrap = []
abbrev = false
width = @columns - @first_indent - @left_margin - @right_margin
indent_str = ' ' * @first_indent
first_line = true
line = words.shift
abbrev = __is_abbrev(line) unless line.nil? || line.empty?
while w = words.shift
if (w.size + line.size < (width - 1)) ||
((line !~ LEQ_RE || abbrev) && (w.size + line.size < width))
line << " " if (line =~ LEQ_RE) && (not abbrev)
line << " #{w}"
else
line, w = __do_break(line, w) if @nobreak
line, w = __do_hyphenate(line, w, width) if @hard_margins
if w.index(/\s+/)
w, *w2 = w.split(/\s+/)
words.unshift(w2)
words.flatten!
end
to_wrap << __make_line(line, indent_str, width, w.nil?) unless line.nil?
if first_line
first_line = false
width = @columns - @body_indent - @left_margin - @right_margin
indent_str = ' ' * @body_indent
end
line = w
end
abbrev = __is_abbrev(w) unless w.nil?
end
loop do
break if line.nil? or line.empty?
line, w = __do_hyphenate(line, w, width) if @hard_margins
to_wrap << __make_line(line, indent_str, width, w.nil?)
line = w
end
if (@tag_paragraph && (to_wrap.size > 0)) then
clr = %r{`(\w+)'}.match([caller(1)].flatten[0])[1]
clr = "" if clr.nil?
if ((not @tag_text[0].nil?) && (@tag_cur.size < 1) &&
(clr != "__paragraphs")) then
@tag_cur = @tag_text[0]
end
fchar = /(\S)/.match(to_wrap[0])[1]
white = to_wrap[0].index(fchar)
if ((white - @left_margin - 1) > @tag_cur.size) then
white = @tag_cur.size + @left_margin
to_wrap[0].gsub!(/^ {#{white}}/, "#{' ' * @left_margin}#{@tag_cur}")
else
to_wrap.unshift("#{' ' * @left_margin}#{@tag_cur}\n")
end
end
to_wrap.join('')
end
# format lines in text into paragraphs with each element of @wrap a
# paragraph; uses Text::Format.format for the formatting
def __paragraphs(to_wrap) #:nodoc:
if ((@first_indent == @body_indent) || @tag_paragraph) then
p_end = "\n"
else
p_end = ''
end
cnt = 0
ret = []
to_wrap.each do |tw|
@tag_cur = @tag_text[cnt] if @tag_paragraph
@tag_cur = '' if @tag_cur.nil?
line = __format(tw)
ret << "#{line}#{p_end}" if (not line.nil?) && (line.size > 0)
cnt += 1
end
ret[-1].chomp! unless ret.empty?
ret.join('')
end
# center text using spaces on left side to pad it out empty lines
# are preserved
def __center(to_center) #:nodoc:
tabs = 0
width = @columns - @left_margin - @right_margin
centered = []
to_center.each do |tc|
s = tc.strip
tabs = s.count("\t")
tabs = 0 if tabs.nil?
ct = ((width - s.size - (tabs * @tabstop) + tabs) / 2)
ct = (width - @left_margin - @right_margin) - ct
centered << "#{s.rjust(ct)}\n"
end
centered.join('')
end
# expand tabs to spaces should be similar to Text::Tabs::expand
def __expand(to_expand) #:nodoc:
expanded = []
to_expand.split("\n").each { |te| expanded << te.gsub(/\t/, ' ' * @tabstop) }
expanded.join('')
end
def __unexpand(to_unexpand) #:nodoc:
unexpanded = []
to_unexpand.split("\n").each { |tu| unexpanded << tu.gsub(/ {#{@tabstop}}/, "\t") }
unexpanded.join('')
end
def __is_abbrev(word) #:nodoc:
# remove period if there is one.
w = word.gsub(/\.$/, '') unless word.nil?
return true if (!@extra_space || ABBREV.include?(w) || @abbreviations.include?(w))
false
end
def __make_line(line, indent, width, last = false) #:nodoc:
lmargin = " " * @left_margin
fill = " " * (width - line.size) if right_fill? && (line.size <= width)
if (justify? && ((not line.nil?) && (not line.empty?)) && line =~ /\S+\s+\S+/ && !last)
spaces = width - line.size
words = line.split(/(\s+)/)
ws = spaces / (words.size / 2)
spaces = spaces % (words.size / 2) if ws > 0
words.reverse.each do |rw|
next if (rw =~ /^\S/)
rw.sub!(/^/, " " * ws)
next unless (spaces > 0)
rw.sub!(/^/, " ")
spaces -= 1
end
line = words.join('')
end
line = "#{lmargin}#{indent}#{line}#{fill}\n" unless line.nil?
if right_align? && (not line.nil?)
line.sub(/^/, " " * (@columns - @right_margin - (line.size - 1)))
else
line
end
end
def __do_hyphenate(line, next_line, width) #:nodoc:
rline = line.dup rescue line
rnext = next_line.dup rescue next_line
loop do
if rline.size == width
break
elsif rline.size > width
words = rline.strip.split(/\s+/)
word = words[-1].dup
size = width - rline.size + word.size
if (size <= 0)
words[-1] = nil
rline = words.join(' ').strip
rnext = "#{word} #{rnext}".strip
next
end
first = rest = nil
if ((@split_rules & SPLIT_HYPHENATION) != 0)
if @hyphenator_arity == 2
first, rest = @hyphenator.hyphenate_to(word, size)
else
first, rest = @hyphenator.hyphenate_to(word, size, self)
end
end
if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
first, rest = self.hyphenate_to(word, size)
end
if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
first.nil? or @split_rules == SPLIT_FIXED
first, rest = __do_split_word(word, size)
end
if first.nil?
words[-1] = nil
rest = word
else
words[-1] = first
@split_words << SplitWord.new(word, first, rest)
end
rline = words.join(' ').strip
rnext = "#{rest} #{rnext}".strip
break
else
break if rnext.nil? or rnext.empty? or rline.nil? or rline.empty?
words = rnext.split(/\s+/)
word = words.shift
size = width - rline.size - 1
if (size <= 0)
rnext = "#{word} #{words.join(' ')}".strip
break
end
first = rest = nil
if ((@split_rules & SPLIT_HYPHENATION) != 0)
if @hyphenator_arity == 2
first, rest = @hyphenator.hyphenate_to(word, size)
else
first, rest = @hyphenator.hyphenate_to(word, size, self)
end
end
first, rest = self.hyphenate_to(word, size) if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
first, rest = __do_split_word(word, size) if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
if (rline.size + (first ? first.size : 0)) < width
@split_words << SplitWord.new(word, first, rest)
rline = "#{rline} #{first}".strip
rnext = "#{rest} #{words.join(' ')}".strip
end
break
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb | require 'tmail/version'
require 'tmail/mail'
require 'tmail/mailbox'
require 'tmail/core_extensions'
require 'tmail/net'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb | #:stopdoc:
require 'tmail/version'
require 'tmail/mail'
require 'tmail/mailbox'
require 'tmail/core_extensions'
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb | =begin rdoc
= Port class
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
require 'tmail/stringio'
module TMail
class Port
def reproducible?
false
end
end
###
### FilePort
###
class FilePort < Port
def initialize( fname )
@filename = File.expand_path(fname)
super()
end
attr_reader :filename
alias ident filename
def ==( other )
other.respond_to?(:filename) and @filename == other.filename
end
alias eql? ==
def hash
@filename.hash
end
def inspect
"#<#{self.class}:#{@filename}>"
end
def reproducible?
true
end
def size
File.size @filename
end
def ropen( &block )
File.open(@filename, &block)
end
def wopen( &block )
File.open(@filename, 'w', &block)
end
def aopen( &block )
File.open(@filename, 'a', &block)
end
def read_all
ropen {|f|
return f.read
}
end
def remove
File.unlink @filename
end
def move_to( port )
begin
File.link @filename, port.filename
rescue Errno::EXDEV
copy_to port
end
File.unlink @filename
end
alias mv move_to
def copy_to( port )
if FilePort === port
copy_file @filename, port.filename
else
File.open(@filename) {|r|
port.wopen {|w|
while s = r.sysread(4096)
w.write << s
end
} }
end
end
alias cp copy_to
private
# from fileutils.rb
def copy_file( src, dest )
st = r = w = nil
File.open(src, 'rb') {|r|
File.open(dest, 'wb') {|w|
st = r.stat
begin
while true
w.write r.sysread(st.blksize)
end
rescue EOFError
end
} }
end
end
module MailFlags
def seen=( b )
set_status 'S', b
end
def seen?
get_status 'S'
end
def replied=( b )
set_status 'R', b
end
def replied?
get_status 'R'
end
def flagged=( b )
set_status 'F', b
end
def flagged?
get_status 'F'
end
private
def procinfostr( str, tag, true_p )
a = str.upcase.split(//)
a.push true_p ? tag : nil
a.delete tag unless true_p
a.compact.sort.join('').squeeze
end
end
class MhPort < FilePort
include MailFlags
private
def set_status( tag, flag )
begin
tmpfile = @filename + '.tmailtmp.' + $$.to_s
File.open(tmpfile, 'w') {|f|
write_status f, tag, flag
}
File.unlink @filename
File.link tmpfile, @filename
ensure
File.unlink tmpfile
end
end
def write_status( f, tag, flag )
stat = ''
File.open(@filename) {|r|
while line = r.gets
if line.strip.empty?
break
elsif m = /\AX-TMail-Status:/i.match(line)
stat = m.post_match.strip
else
f.print line
end
end
s = procinfostr(stat, tag, flag)
f.puts 'X-TMail-Status: ' + s unless s.empty?
f.puts
while s = r.read(2048)
f.write s
end
}
end
def get_status( tag )
File.foreach(@filename) {|line|
return false if line.strip.empty?
if m = /\AX-TMail-Status:/i.match(line)
return m.post_match.strip.include?(tag[0])
end
}
false
end
end
class MaildirPort < FilePort
def move_to_new
new = replace_dir(@filename, 'new')
File.rename @filename, new
@filename = new
end
def move_to_cur
new = replace_dir(@filename, 'cur')
File.rename @filename, new
@filename = new
end
def replace_dir( path, dir )
"#{File.dirname File.dirname(path)}/#{dir}/#{File.basename path}"
end
private :replace_dir
include MailFlags
private
MAIL_FILE = /\A(\d+\.[\d_]+\.[^:]+)(?:\:(\d),(\w+)?)?\z/
def set_status( tag, flag )
if m = MAIL_FILE.match(File.basename(@filename))
s, uniq, type, info, = m.to_a
return if type and type != '2' # do not change anything
newname = File.dirname(@filename) + '/' +
uniq + ':2,' + procinfostr(info.to_s, tag, flag)
else
newname = @filename + ':2,' + tag
end
File.link @filename, newname
File.unlink @filename
@filename = newname
end
def get_status( tag )
m = MAIL_FILE.match(File.basename(@filename)) or return false
m[2] == '2' and m[3].to_s.include?(tag[0])
end
end
###
### StringPort
###
class StringPort < Port
def initialize( str = '' )
@buffer = str
super()
end
def string
@buffer
end
def to_s
@buffer.dup
end
alias read_all to_s
def size
@buffer.size
end
def ==( other )
StringPort === other and @buffer.equal? other.string
end
alias eql? ==
def hash
@buffer.object_id.hash
end
def inspect
"#<#{self.class}:id=#{sprintf '0x%x', @buffer.object_id}>"
end
def reproducible?
true
end
def ropen( &block )
@buffer or raise Errno::ENOENT, "#{inspect} is already removed"
StringInput.open(@buffer, &block)
end
def wopen( &block )
@buffer = ''
StringOutput.new(@buffer, &block)
end
def aopen( &block )
@buffer ||= ''
StringOutput.new(@buffer, &block)
end
def remove
@buffer = nil
end
alias rm remove
def copy_to( port )
port.wopen {|f|
f.write @buffer
}
end
alias cp copy_to
def move_to( port )
if StringPort === port
str = @buffer
port.instance_eval { @buffer = str }
else
copy_to port
end
remove
end
end
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb | #
# version.rb
#
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
module TMail
module VERSION
MAJOR = 1
MINOR = 2
TINY = 3
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb | #:stopdoc:
require 'rbconfig'
# Attempts to require anative extension.
# Falls back to pure-ruby version, if it fails.
#
# This uses Config::CONFIG['arch'] from rbconfig.
def require_arch(fname)
arch = Config::CONFIG['arch']
begin
path = File.join("tmail", arch, fname)
require path
rescue LoadError => e
# try pre-built Windows binaries
if arch =~ /mswin/
require File.join("tmail", 'mswin32', fname)
else
raise e
end
end
end
# def require_arch(fname)
# dext = Config::CONFIG['DLEXT']
# begin
# if File.extname(fname) == dext
# path = fname
# else
# path = File.join("tmail","#{fname}.#{dext}")
# end
# require path
# rescue LoadError => e
# begin
# arch = Config::CONFIG['arch']
# path = File.join("tmail", arch, "#{fname}.#{dext}")
# require path
# rescue LoadError
# case path
# when /i686/
# path.sub!('i686', 'i586')
# when /i586/
# path.sub!('i586', 'i486')
# when /i486/
# path.sub!('i486', 'i386')
# else
# begin
# require fname + '.rb'
# rescue LoadError
# raise e
# end
# end
# retry
# end
# end
# end
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb | #:stopdoc:
unless Object.respond_to?(:blank?)
class Object
# Check first to see if we are in a Rails environment, no need to
# define these methods if we are
# An object is blank if it's nil, empty, or a whitespace string.
# For example, "", " ", nil, [], and {} are blank.
#
# This simplifies
# if !address.nil? && !address.empty?
# to
# if !address.blank?
def blank?
if respond_to?(:empty?) && respond_to?(:strip)
empty? or strip.empty?
elsif respond_to?(:empty?)
empty?
else
!self
end
end
end
class NilClass
def blank?
true
end
end
class FalseClass
def blank?
true
end
end
class TrueClass
def blank?
false
end
end
class Array
alias_method :blank?, :empty?
end
class Hash
alias_method :blank?, :empty?
end
class String
def blank?
empty? || strip.empty?
end
end
class Numeric
def blank?
false
end
end
end
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb | # encoding: utf-8
=begin rdoc
= String handling class
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
class StringInput#:nodoc:
include Enumerable
class << self
def new( str )
if block_given?
begin
f = super
yield f
ensure
f.close if f
end
else
super
end
end
alias open new
end
def initialize( str )
@src = str
@pos = 0
@closed = false
@lineno = 0
end
attr_reader :lineno
def string
@src
end
def inspect
"#<#{self.class}:#{@closed ? 'closed' : 'open'},src=#{@src[0,30].inspect}>"
end
def close
stream_check!
@pos = nil
@closed = true
end
def closed?
@closed
end
def pos
stream_check!
[@pos, @src.size].min
end
alias tell pos
def seek( offset, whence = IO::SEEK_SET )
stream_check!
case whence
when IO::SEEK_SET
@pos = offset
when IO::SEEK_CUR
@pos += offset
when IO::SEEK_END
@pos = @src.size - offset
else
raise ArgumentError, "unknown seek flag: #{whence}"
end
@pos = 0 if @pos < 0
@pos = [@pos, @src.size + 1].min
offset
end
def rewind
stream_check!
@pos = 0
end
def eof?
stream_check!
@pos > @src.size
end
def each( &block )
stream_check!
begin
@src.each(&block)
ensure
@pos = 0
end
end
def gets
stream_check!
if idx = @src.index(?\n, @pos)
idx += 1 # "\n".size
line = @src[ @pos ... idx ]
@pos = idx
@pos += 1 if @pos == @src.size
else
line = @src[ @pos .. -1 ]
@pos = @src.size + 1
end
@lineno += 1
line
end
def getc
stream_check!
ch = @src[@pos]
@pos += 1
@pos += 1 if @pos == @src.size
ch
end
def read( len = nil )
stream_check!
return read_all unless len
str = @src[@pos, len]
@pos += len
@pos += 1 if @pos == @src.size
str
end
alias sysread read
def read_all
stream_check!
return nil if eof?
rest = @src[@pos ... @src.size]
@pos = @src.size + 1
rest
end
def stream_check!
@closed and raise IOError, 'closed stream'
end
end
class StringOutput#:nodoc:
class << self
def new( str = '' )
if block_given?
begin
f = super
yield f
ensure
f.close if f
end
else
super
end
end
alias open new
end
def initialize( str = '' )
@dest = str
@closed = false
end
def close
@closed = true
end
def closed?
@closed
end
def string
@dest
end
alias value string
alias to_str string
def size
@dest.size
end
alias pos size
def inspect
"#<#{self.class}:#{@dest ? 'open' : 'closed'},#{object_id}>"
end
def print( *args )
stream_check!
raise ArgumentError, 'wrong # of argument (0 for >1)' if args.empty?
args.each do |s|
raise ArgumentError, 'nil not allowed' if s.nil?
@dest << s.to_s
end
nil
end
def puts( *args )
stream_check!
args.each do |str|
@dest << (s = str.to_s)
@dest << "\n" unless s[-1] == ?\n
end
@dest << "\n" if args.empty?
nil
end
def putc( ch )
stream_check!
@dest << ch.chr
nil
end
def printf( *args )
stream_check!
@dest << sprintf(*args)
nil
end
def write( str )
stream_check!
s = str.to_s
@dest << s
s.size
end
alias syswrite write
def <<( str )
stream_check!
@dest << str.to_s
self
end
private
def stream_check!
@closed and raise IOError, 'closed stream'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb | =begin rdoc
= Attachment handling file
=end
require 'stringio'
module TMail
class Attachment < StringIO
attr_accessor :original_filename, :content_type
end
class Mail
def has_attachments?
multipart? && parts.any? { |part| attachment?(part) }
end
def attachment?(part)
part.disposition_is_attachment? || part.content_type_is_text?
end
def attachments
if multipart?
parts.collect { |part|
if part.multipart?
part.attachments
elsif attachment?(part)
content = part.body # unquoted automatically by TMail#body
file_name = (part['content-location'] &&
part['content-location'].body) ||
part.sub_header("content-type", "name") ||
part.sub_header("content-disposition", "filename")
next if file_name.blank? || content.blank?
attachment = Attachment.new(content)
attachment.original_filename = file_name.strip
attachment.content_type = part.content_type
attachment
end
}.flatten.compact
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb | #:stopdoc:
# This is here for Rolls.
# Rolls uses this instead of lib/tmail.rb.
require 'tmail/version'
require 'tmail/mail'
require 'tmail/mailbox'
require 'tmail/core_extensions'
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb | #:stopdoc:
require 'tmail/mailbox'
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb | =begin rdoc
= interface.rb Provides an interface to the TMail object
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
# TMail::Mail objects get accessed primarily through the methods in this file.
#
#
require 'tmail/utils'
module TMail
class Mail
# Allows you to query the mail object with a string to get the contents
# of the field you want.
#
# Returns a string of the exact contents of the field
#
# mail.from = "mikel <mikel@lindsaar.net>"
# mail.header_string("From") #=> "mikel <mikel@lindsaar.net>"
def header_string( name, default = nil )
h = @header[name.downcase] or return default
h.to_s
end
#:stopdoc:
#--
#== Attributes
include TextUtils
def set_string_array_attr( key, strs )
strs.flatten!
if strs.empty?
@header.delete key.downcase
else
store key, strs.join(', ')
end
strs
end
private :set_string_array_attr
def set_string_attr( key, str )
if str
store key, str
else
@header.delete key.downcase
end
str
end
private :set_string_attr
def set_addrfield( name, arg )
if arg
h = HeaderField.internal_new(name, @config)
h.addrs.replace [arg].flatten
@header[name] = h
else
@header.delete name
end
arg
end
private :set_addrfield
def addrs2specs( addrs )
return nil unless addrs
list = addrs.map {|addr|
if addr.address_group?
then addr.map {|a| a.spec }
else addr.spec
end
}.flatten
return nil if list.empty?
list
end
private :addrs2specs
#:startdoc:
#== Date and Time methods
# Returns the date of the email message as per the "date" header value or returns
# nil by default (if no date field exists).
#
# You can also pass whatever default you want into this method and it will return
# that instead of nil if there is no date already set.
def date( default = nil )
if h = @header['date']
h.date
else
default
end
end
# Destructively sets the date of the mail object with the passed Time instance,
# returns a Time instance set to the date/time of the mail
#
# Example:
#
# now = Time.now
# mail.date = now
# mail.date #=> Sat Nov 03 18:47:50 +1100 2007
# mail.date.class #=> Time
def date=( time )
if time
store 'Date', time2str(time)
else
@header.delete 'date'
end
time
end
# Returns the time of the mail message formatted to your taste using a
# strftime format string. If no date set returns nil by default or whatever value
# you pass as the second optional parameter.
#
# time = Time.now # (on Nov 16 2007)
# mail.date = time
# mail.strftime("%D") #=> "11/16/07"
def strftime( fmt, default = nil )
if t = date
t.strftime(fmt)
else
default
end
end
#== Destination methods
# Return a TMail::Addresses instance for each entry in the "To:" field of the mail object header.
#
# If the "To:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.to_addrs #=> nil
# mail.to_addrs([]) #=> []
# mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def to_addrs( default = nil )
if h = @header['to']
h.addrs
else
default
end
end
# Return a TMail::Addresses instance for each entry in the "Cc:" field of the mail object header.
#
# If the "Cc:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.cc_addrs #=> nil
# mail.cc_addrs([]) #=> []
# mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def cc_addrs( default = nil )
if h = @header['cc']
h.addrs
else
default
end
end
# Return a TMail::Addresses instance for each entry in the "Bcc:" field of the mail object header.
#
# If the "Bcc:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.bcc_addrs #=> nil
# mail.bcc_addrs([]) #=> []
# mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def bcc_addrs( default = nil )
if h = @header['bcc']
h.addrs
else
default
end
end
# Destructively set the to field of the "To:" header to equal the passed in string.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def to_addrs=( arg )
set_addrfield 'to', arg
end
# Destructively set the to field of the "Cc:" header to equal the passed in string.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def cc_addrs=( arg )
set_addrfield 'cc', arg
end
# Destructively set the to field of the "Bcc:" header to equal the passed in string.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def bcc_addrs=( arg )
set_addrfield 'bcc', arg
end
# Returns who the email is to as an Array of email addresses as opposed to an Array of
# TMail::Address objects which is what Mail#to_addrs returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.to #=> ["mikel@me.org", "mikel@you.org"]
def to( default = nil )
addrs2specs(to_addrs(nil)) || default
end
# Returns who the email cc'd as an Array of email addresses as opposed to an Array of
# TMail::Address objects which is what Mail#to_addrs returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.cc #=> ["mikel@me.org", "mikel@you.org"]
def cc( default = nil )
addrs2specs(cc_addrs(nil)) || default
end
# Returns who the email bcc'd as an Array of email addresses as opposed to an Array of
# TMail::Address objects which is what Mail#to_addrs returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.bcc #=> ["mikel@me.org", "mikel@you.org"]
def bcc( default = nil )
addrs2specs(bcc_addrs(nil)) || default
end
# Destructively sets the "To:" field to the passed array of strings (which should be valid
# email addresses)
#
# Example:
#
# mail = TMail::Mail.new
# mail.to = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
# mail.to #=> ["mikel@abc.org", "mikel@xyz.org"]
# mail['to'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
def to=( *strs )
set_string_array_attr 'To', strs
end
# Destructively sets the "Cc:" field to the passed array of strings (which should be valid
# email addresses)
#
# Example:
#
# mail = TMail::Mail.new
# mail.cc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
# mail.cc #=> ["mikel@abc.org", "mikel@xyz.org"]
# mail['cc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
def cc=( *strs )
set_string_array_attr 'Cc', strs
end
# Destructively sets the "Bcc:" field to the passed array of strings (which should be valid
# email addresses)
#
# Example:
#
# mail = TMail::Mail.new
# mail.bcc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
# mail.bcc #=> ["mikel@abc.org", "mikel@xyz.org"]
# mail['bcc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
def bcc=( *strs )
set_string_array_attr 'Bcc', strs
end
#== Originator methods
# Return a TMail::Addresses instance for each entry in the "From:" field of the mail object header.
#
# If the "From:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.from_addrs #=> nil
# mail.from_addrs([]) #=> []
# mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def from_addrs( default = nil )
if h = @header['from']
h.addrs
else
default
end
end
# Destructively set the to value of the "From:" header to equal the passed in string.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.from_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def from_addrs=( arg )
set_addrfield 'from', arg
end
# Returns who the email is from as an Array of email address strings instead to an Array of
# TMail::Address objects which is what Mail#from_addrs returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.from #=> ["mikel@me.org", "mikel@you.org"]
def from( default = nil )
addrs2specs(from_addrs(nil)) || default
end
# Destructively sets the "From:" field to the passed array of strings (which should be valid
# email addresses)
#
# Example:
#
# mail = TMail::Mail.new
# mail.from = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
# mail.from #=> ["mikel@abc.org", "mikel@xyz.org"]
# mail['from'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
def from=( *strs )
set_string_array_attr 'From', strs
end
# Returns the "friendly" human readable part of the address
#
# Example:
#
# mail = TMail::Mail.new
# mail.from = "Mikel Lindsaar <mikel@abc.com>"
# mail.friendly_from #=> "Mikel Lindsaar"
def friendly_from( default = nil )
h = @header['from']
a, = h.addrs
return default unless a
return a.phrase if a.phrase
return h.comments.join(' ') unless h.comments.empty?
a.spec
end
# Return a TMail::Addresses instance for each entry in the "Reply-To:" field of the mail object header.
#
# If the "Reply-To:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.reply_to_addrs #=> nil
# mail.reply_to_addrs([]) #=> []
# mail.reply_to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def reply_to_addrs( default = nil )
if h = @header['reply-to']
h.addrs.blank? ? default : h.addrs
else
default
end
end
# Destructively set the to value of the "Reply-To:" header to equal the passed in argument.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.reply_to_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def reply_to_addrs=( arg )
set_addrfield 'reply-to', arg
end
# Returns who the email is from as an Array of email address strings instead to an Array of
# TMail::Address objects which is what Mail#reply_to_addrs returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.reply_to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.reply_to #=> ["mikel@me.org", "mikel@you.org"]
def reply_to( default = nil )
addrs2specs(reply_to_addrs(nil)) || default
end
# Destructively sets the "Reply-To:" field to the passed array of strings (which should be valid
# email addresses)
#
# Example:
#
# mail = TMail::Mail.new
# mail.reply_to = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
# mail.reply_to #=> ["mikel@abc.org", "mikel@xyz.org"]
# mail['reply_to'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
def reply_to=( *strs )
set_string_array_attr 'Reply-To', strs
end
# Return a TMail::Addresses instance of the "Sender:" field of the mail object header.
#
# If the "Sender:" field does not exist, will return nil by default or the value you
# pass as the optional parameter.
#
# Example:
#
# mail = TMail::Mail.new
# mail.sender #=> nil
# mail.sender([]) #=> []
# mail.sender = "Mikel <mikel@me.org>"
# mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>]
def sender_addr( default = nil )
f = @header['sender'] or return default
f.addr or return default
end
# Destructively set the to value of the "Sender:" header to equal the passed in argument.
#
# TMail will parse your contents and turn each valid email address into a TMail::Address
# object before assigning it to the mail message.
#
# Example:
#
# mail = TMail::Mail.new
# mail.sender_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
# mail.sender_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
def sender_addr=( addr )
if addr
h = HeaderField.internal_new('sender', @config)
h.addr = addr
@header['sender'] = h
else
@header.delete 'sender'
end
addr
end
# Returns who the sender of this mail is as string instead to an Array of
# TMail::Address objects which is what Mail#sender_addr returns
#
# Example:
#
# mail = TMail::Mail.new
# mail.sender = "Mikel <mikel@me.org>"
# mail.sender #=> "mikel@me.org"
def sender( default = nil )
f = @header['sender'] or return default
a = f.addr or return default
a.spec
end
# Destructively sets the "Sender:" field to the passed string (which should be a valid
# email address)
#
# Example:
#
# mail = TMail::Mail.new
# mail.sender = "mikel@abc.com"
# mail.sender #=> "mikel@abc.org"
# mail['sender'].to_s #=> "mikel@abc.com"
def sender=( str )
set_string_attr 'Sender', str
end
#== Subject methods
# Returns the subject of the mail instance.
#
# If the subject field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.subject #=> nil
# mail.subject("") #=> ""
# mail.subject = "Hello"
# mail.subject #=> "Hello"
def subject( default = nil )
if h = @header['subject']
h.body
else
default
end
end
alias quoted_subject subject
# Destructively sets the passed string as the subject of the mail message.
#
# Example
#
# mail = TMail::Mail.new
# mail.subject #=> "This subject"
# mail.subject = "Another subject"
# mail.subject #=> "Another subject"
def subject=( str )
set_string_attr 'Subject', str
end
#== Message Identity & Threading Methods
# Returns the message ID for this mail object instance.
#
# If the message_id field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.message_id #=> nil
# mail.message_id(TMail.new_message_id) #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>"
# mail.message_id = TMail.new_message_id
# mail.message_id #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>"
def message_id( default = nil )
if h = @header['message-id']
h.id || default
else
default
end
end
# Destructively sets the message ID of the mail object instance to the passed in string
#
# Invalid message IDs are ignored (silently, unless configured otherwise) and result in
# a nil message ID. Left and right angle brackets are required.
#
# Example:
#
# mail = TMail::Mail.new
# mail.message_id = "<348F04F142D69C21-291E56D292BC@xxxx.net>"
# mail.message_id #=> "<348F04F142D69C21-291E56D292BC@xxxx.net>"
# mail.message_id = "this_is_my_badly_formatted_message_id"
# mail.message_id #=> nil
def message_id=( str )
set_string_attr 'Message-Id', str
end
# Returns the "In-Reply-To:" field contents as an array of this mail instance if it exists
#
# If the in_reply_to field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.in_reply_to #=> nil
# mail.in_reply_to([]) #=> []
# TMail::Mail.load("../test/fixtures/raw_email_reply")
# mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
def in_reply_to( default = nil )
if h = @header['in-reply-to']
h.ids
else
default
end
end
# Destructively sets the value of the "In-Reply-To:" field of an email.
#
# Accepts an array of a single string of a message id
#
# Example:
#
# mail = TMail::Mail.new
# mail.in_reply_to = ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
# mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
def in_reply_to=( *idstrs )
set_string_array_attr 'In-Reply-To', idstrs
end
# Returns the references of this email (prior messages relating to this message)
# as an array of message ID strings. Useful when you are trying to thread an
# email.
#
# If the references field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.references #=> nil
# mail.references([]) #=> []
# mail = TMail::Mail.load("../test/fixtures/raw_email_reply")
# mail.references #=> ["<473FF3B8.9020707@xxx.org>", "<348F04F142D69C21-291E56D292BC@xxxx.net>"]
def references( default = nil )
if h = @header['references']
h.refs
else
default
end
end
# Destructively sets the value of the "References:" field of an email.
#
# Accepts an array of strings of message IDs
#
# Example:
#
# mail = TMail::Mail.new
# mail.references = ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
# mail.references #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
def references=( *strs )
set_string_array_attr 'References', strs
end
#== MIME header methods
# Returns the listed MIME version of this email from the "Mime-Version:" header field
#
# If the mime_version field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.mime_version #=> nil
# mail.mime_version([]) #=> []
# mail = TMail::Mail.load("../test/fixtures/raw_email")
# mail.mime_version #=> "1.0"
def mime_version( default = nil )
if h = @header['mime-version']
h.version || default
else
default
end
end
def mime_version=( m, opt = nil )
if opt
if h = @header['mime-version']
h.major = m
h.minor = opt
else
store 'Mime-Version', "#{m}.#{opt}"
end
else
store 'Mime-Version', m
end
m
end
# Returns the current "Content-Type" of the mail instance.
#
# If the content_type field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.content_type #=> nil
# mail.content_type([]) #=> []
# mail = TMail::Mail.load("../test/fixtures/raw_email")
# mail.content_type #=> "text/plain"
def content_type( default = nil )
if h = @header['content-type']
h.content_type || default
else
default
end
end
# Returns the current main type of the "Content-Type" of the mail instance.
#
# If the content_type field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.main_type #=> nil
# mail.main_type([]) #=> []
# mail = TMail::Mail.load("../test/fixtures/raw_email")
# mail.main_type #=> "text"
def main_type( default = nil )
if h = @header['content-type']
h.main_type || default
else
default
end
end
# Returns the current sub type of the "Content-Type" of the mail instance.
#
# If the content_type field does not exist, returns nil by default or you can pass in as
# the parameter for what you want the default value to be.
#
# Example:
#
# mail = TMail::Mail.new
# mail.sub_type #=> nil
# mail.sub_type([]) #=> []
# mail = TMail::Mail.load("../test/fixtures/raw_email")
# mail.sub_type #=> "plain"
def sub_type( default = nil )
if h = @header['content-type']
h.sub_type || default
else
default
end
end
# Destructively sets the "Content-Type:" header field of this mail object
#
# Allows you to set the main type, sub type as well as parameters to the field.
# The main type and sub type need to be a string.
#
# The optional params hash can be passed with keys as symbols and values as a string,
# or strings as keys and values.
#
# Example:
#
# mail = TMail::Mail.new
# mail.set_content_type("text", "plain")
# mail.to_s #=> "Content-Type: text/plain\n\n"
#
# mail.set_content_type("text", "plain", {:charset => "EUC-KR", :format => "flowed"})
# mail.to_s #=> "Content-Type: text/plain; charset=EUC-KR; format=flowed\n\n"
#
# mail.set_content_type("text", "plain", {"charset" => "EUC-KR", "format" => "flowed"})
# mail.to_s #=> "Content-Type: text/plain; charset=EUC-KR; format=flowed\n\n"
def set_content_type( str, sub = nil, param = nil )
if sub
main, sub = str, sub
else
main, sub = str.split(%r</>, 2)
raise ArgumentError, "sub type missing: #{str.inspect}" unless sub
end
if h = @header['content-type']
h.main_type = main
h.sub_type = sub
h.params.clear
else
store 'Content-Type', "#{main}/#{sub}"
end
@header['content-type'].params.replace param if param
str
end
alias content_type= set_content_type
# Returns the named type parameter as a string, from the "Content-Type:" header.
#
# Example:
#
# mail = TMail::Mail.new
# mail.type_param("charset") #=> nil
# mail.type_param("charset", []) #=> []
# mail.set_content_type("text", "plain", {:charset => "EUC-KR", :format => "flowed"})
# mail.type_param("charset") #=> "EUC-KR"
# mail.type_param("format") #=> "flowed"
def type_param( name, default = nil )
if h = @header['content-type']
h[name] || default
else
default
end
end
# Returns the character set of the email. Returns nil if no encoding set or returns
# whatever default you pass as a parameter - note passing the parameter does NOT change
# the mail object in any way.
#
# Example:
#
# mail = TMail::Mail.load("path_to/utf8_email")
# mail.charset #=> "UTF-8"
#
# mail = TMail::Mail.new
# mail.charset #=> nil
# mail.charset("US-ASCII") #=> "US-ASCII"
def charset( default = nil )
if h = @header['content-type']
h['charset'] or default
else
default
end
end
# Destructively sets the character set used by this mail object to the passed string, you
# should note though that this does nothing to the mail body, just changes the header
# value, you will need to transliterate the body as well to match whatever you put
# in this header value if you are changing character sets.
#
# Example:
#
# mail = TMail::Mail.new
# mail.charset #=> nil
# mail.charset = "UTF-8"
# mail.charset #=> "UTF-8"
def charset=( str )
if str
if h = @header[ 'content-type' ]
h['charset'] = str
else
store 'Content-Type', "text/plain; charset=#{str}"
end
end
str
end
# Returns the transfer encoding of the email. Returns nil if no encoding set or returns
# whatever default you pass as a parameter - note passing the parameter does NOT change
# the mail object in any way.
#
# Example:
#
# mail = TMail::Mail.load("path_to/base64_encoded_email")
# mail.transfer_encoding #=> "base64"
#
# mail = TMail::Mail.new
# mail.transfer_encoding #=> nil
# mail.transfer_encoding("base64") #=> "base64"
def transfer_encoding( default = nil )
if h = @header['content-transfer-encoding']
h.encoding || default
else
default
end
end
# Destructively sets the transfer encoding of the mail object to the passed string, you
# should note though that this does nothing to the mail body, just changes the header
# value, you will need to encode or decode the body as well to match whatever you put
# in this header value.
#
# Example:
#
# mail = TMail::Mail.new
# mail.transfer_encoding #=> nil
# mail.transfer_encoding = "base64"
# mail.transfer_encoding #=> "base64"
def transfer_encoding=( str )
set_string_attr 'Content-Transfer-Encoding', str
end
alias encoding transfer_encoding
alias encoding= transfer_encoding=
alias content_transfer_encoding transfer_encoding
alias content_transfer_encoding= transfer_encoding=
# Returns the content-disposition of the mail object, returns nil or the passed
# default value if given
#
# Example:
#
# mail = TMail::Mail.load("path_to/raw_mail_with_attachment")
# mail.disposition #=> "attachment"
#
# mail = TMail::Mail.load("path_to/plain_simple_email")
# mail.disposition #=> nil
# mail.disposition(false) #=> false
def disposition( default = nil )
if h = @header['content-disposition']
h.disposition || default
else
default
end
end
alias content_disposition disposition
# Allows you to set the content-disposition of the mail object. Accepts a type
# and a hash of parameters.
#
# Example:
#
# mail.set_disposition("attachment", {:filename => "test.rb"})
# mail.disposition #=> "attachment"
# mail['content-disposition'].to_s #=> "attachment; filename=test.rb"
def set_disposition( str, params = nil )
if h = @header['content-disposition']
h.disposition = str
h.params.clear
else
store('Content-Disposition', str)
h = @header['content-disposition']
end
h.params.replace params if params
end
alias disposition= set_disposition
alias set_content_disposition set_disposition
alias content_disposition= set_disposition
# Returns the value of a parameter in an existing content-disposition header
#
# Example:
#
# mail.set_disposition("attachment", {:filename => "test.rb"})
# mail['content-disposition'].to_s #=> "attachment; filename=test.rb"
# mail.disposition_param("filename") #=> "test.rb"
# mail.disposition_param("missing_param_key") #=> nil
# mail.disposition_param("missing_param_key", false) #=> false
# mail.disposition_param("missing_param_key", "Nothing to see here") #=> "Nothing to see here"
def disposition_param( name, default = nil )
if h = @header['content-disposition']
h[name] || default
else
default
end
end
# Convert the Mail object's body into a Base64 encoded email
# returning the modified Mail object
def base64_encode!
store 'Content-Transfer-Encoding', 'Base64'
self.body = base64_encode
end
# Return the result of encoding the TMail::Mail object body
# without altering the current body
def base64_encode
Base64.folding_encode(self.body)
end
# Convert the Mail object's body into a Base64 decoded email
# returning the modified Mail object
def base64_decode!
if /base64/i === self.transfer_encoding('')
store 'Content-Transfer-Encoding', '8bit'
self.body = base64_decode
end
end
# Returns the result of decoding the TMail::Mail object body
# without altering the current body
def base64_decode
Base64.decode(self.body, @config.strict_base64decode?)
end
# Returns an array of each destination in the email message including to: cc: or bcc:
#
# Example:
#
# mail.to = "Mikel <mikel@lindsaar.net>"
# mail.cc = "Trans <t@t.com>"
# mail.bcc = "bob <bob@me.com>"
# mail.destinations #=> ["mikel@lindsaar.net", "t@t.com", "bob@me.com"]
def destinations( default = nil )
ret = []
%w( to cc bcc ).each do |nm|
if h = @header[nm]
h.addrs.each {|i| ret.push i.address }
end
end
ret.empty? ? default : ret
end
# Yields a block of destination, yielding each as a string.
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb | #--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
# = TMail - The EMail Swiss Army Knife for Ruby
#
# The TMail library provides you with a very complete way to handle and manipulate EMails
# from within your Ruby programs.
#
# Used as the backbone for email handling by the Ruby on Rails and Nitro web frameworks as
# well as a bunch of other Ruby apps including the Ruby-Talk mailing list to newsgroup email
# gateway, it is a proven and reliable email handler that won't let you down.
#
# Originally created by Minero Aoki, TMail has been recently picked up by Mikel Lindsaar and
# is being actively maintained. Numerous backlogged bug fixes have been applied as well as
# Ruby 1.9 compatibility and a swath of documentation to boot.
#
# TMail allows you to treat an email totally as an object and allow you to get on with your
# own programming without having to worry about crafting the perfect email address validation
# parser, or assembling an email from all it's component parts.
#
# TMail handles the most complex part of the email - the header. It generates and parses
# headers and provides you with instant access to their innards through simple and logically
# named accessor and setter methods.
#
# TMail also provides a wrapper to Net/SMTP as well as Unix Mailbox handling methods to
# directly read emails from your unix mailbox, parse them and use them.
#
# Following is the comprehensive list of methods to access TMail::Mail objects. You can also
# check out TMail::Mail, TMail::Address and TMail::Headers for other lists.
module TMail
# Provides an exception to throw on errors in Syntax within TMail's parsers
class SyntaxError < StandardError; end
# Provides a new email boundary to separate parts of the email. This is a random
# string based off the current time, so should be fairly unique.
#
# For Example:
#
# TMail.new_boundary
# #=> "mimepart_47bf656968207_25a8fbb80114"
# TMail.new_boundary
# #=> "mimepart_47bf66051de4_25a8fbb80240"
def TMail.new_boundary
'mimepart_' + random_tag
end
# Provides a new email message ID. You can use this to generate unique email message
# id's for your email so you can track them.
#
# Optionally takes a fully qualified domain name (default to the current hostname
# returned by Socket.gethostname) that will be appended to the message ID.
#
# For Example:
#
# email.message_id = TMail.new_message_id
# #=> "<47bf66845380e_25a8fbb80332@baci.local.tmail>"
# email.to_s
# #=> "Message-Id: <47bf668b633f1_25a8fbb80475@baci.local.tmail>\n\n"
# email.message_id = TMail.new_message_id("lindsaar.net")
# #=> "<47bf668b633f1_25a8fbb80475@lindsaar.net.tmail>"
# email.to_s
# #=> "Message-Id: <47bf668b633f1_25a8fbb80475@lindsaar.net.tmail>\n\n"
def TMail.new_message_id( fqdn = nil )
fqdn ||= ::Socket.gethostname
"<#{random_tag()}@#{fqdn}.tmail>"
end
#:stopdoc:
def TMail.random_tag #:nodoc:
@uniq += 1
t = Time.now
sprintf('%x%x_%x%x%d%x',
t.to_i, t.tv_usec,
$$, Thread.current.object_id, @uniq, rand(255))
end
private_class_method :random_tag
@uniq = 0
#:startdoc:
# Text Utils provides a namespace to define TOKENs, ATOMs, PHRASEs and CONTROL characters that
# are OK per RFC 2822.
#
# It also provides methods you can call to determine if a string is safe
module TextUtils
aspecial = %Q|()<>[]:;.\\,"|
tspecial = %Q|()<>[];:\\,"/?=|
lwsp = %Q| \t\r\n|
control = %Q|\x00-\x1f\x7f-\xff|
CONTROL_CHAR = /[#{control}]/n
ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{lwsp}]/n
PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{lwsp}]/n
# Returns true if the string supplied is free from characters not allowed as an ATOM
def atom_safe?( str )
not ATOM_UNSAFE === str
end
# If the string supplied has ATOM unsafe characters in it, will return the string quoted
# in double quotes, otherwise returns the string unmodified
def quote_atom( str )
(ATOM_UNSAFE === str) ? dquote(str) : str
end
# If the string supplied has PHRASE unsafe characters in it, will return the string quoted
# in double quotes, otherwise returns the string unmodified
def quote_phrase( str )
(PHRASE_UNSAFE === str) ? dquote(str) : str
end
# Returns true if the string supplied is free from characters not allowed as a TOKEN
def token_safe?( str )
not TOKEN_UNSAFE === str
end
# If the string supplied has TOKEN unsafe characters in it, will return the string quoted
# in double quotes, otherwise returns the string unmodified
def quote_token( str )
(TOKEN_UNSAFE === str) ? dquote(str) : str
end
# Wraps supplied string in double quotes unless it is already wrapped
# Returns double quoted string
def dquote( str ) #:nodoc:
unless str =~ /^".*?"$/
'"' + str.gsub(/["\\]/n) {|s| '\\' + s } + '"'
else
str
end
end
private :dquote
# Unwraps supplied string from inside double quotes
# Returns unquoted string
def unquote( str )
str =~ /^"(.*?)"$/ ? $1 : str
end
# Provides a method to join a domain name by it's parts and also makes it
# ATOM safe by quoting it as needed
def join_domain( arr )
arr.map {|i|
if /\A\[.*\]\z/ === i
i
else
quote_atom(i)
end
}.join('.')
end
#:stopdoc:
ZONESTR_TABLE = {
'jst' => 9 * 60,
'eet' => 2 * 60,
'bst' => 1 * 60,
'met' => 1 * 60,
'gmt' => 0,
'utc' => 0,
'ut' => 0,
'nst' => -(3 * 60 + 30),
'ast' => -4 * 60,
'edt' => -4 * 60,
'est' => -5 * 60,
'cdt' => -5 * 60,
'cst' => -6 * 60,
'mdt' => -6 * 60,
'mst' => -7 * 60,
'pdt' => -7 * 60,
'pst' => -8 * 60,
'a' => -1 * 60,
'b' => -2 * 60,
'c' => -3 * 60,
'd' => -4 * 60,
'e' => -5 * 60,
'f' => -6 * 60,
'g' => -7 * 60,
'h' => -8 * 60,
'i' => -9 * 60,
# j not use
'k' => -10 * 60,
'l' => -11 * 60,
'm' => -12 * 60,
'n' => 1 * 60,
'o' => 2 * 60,
'p' => 3 * 60,
'q' => 4 * 60,
'r' => 5 * 60,
's' => 6 * 60,
't' => 7 * 60,
'u' => 8 * 60,
'v' => 9 * 60,
'w' => 10 * 60,
'x' => 11 * 60,
'y' => 12 * 60,
'z' => 0 * 60
}
#:startdoc:
# Takes a time zone string from an EMail and converts it to Unix Time (seconds)
def timezone_string_to_unixtime( str )
if m = /([\+\-])(\d\d?)(\d\d)/.match(str)
sec = (m[2].to_i * 60 + m[3].to_i) * 60
m[1] == '-' ? -sec : sec
else
min = ZONESTR_TABLE[str.downcase] or
raise SyntaxError, "wrong timezone format '#{str}'"
min * 60
end
end
#:stopdoc:
WDAY = %w( Sun Mon Tue Wed Thu Fri Sat TMailBUG )
MONTH = %w( TMailBUG Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec TMailBUG )
def time2str( tm )
# [ruby-list:7928]
gmt = Time.at(tm.to_i)
gmt.gmtime
offset = tm.to_i - Time.local(*gmt.to_a[0,6].reverse).to_i
# DO NOT USE strftime: setlocale() breaks it
sprintf '%s, %s %s %d %02d:%02d:%02d %+.2d%.2d',
WDAY[tm.wday], tm.mday, MONTH[tm.month],
tm.year, tm.hour, tm.min, tm.sec,
*(offset / 60).divmod(60)
end
MESSAGE_ID = /<[^\@>]+\@[^>\@]+>/
def message_id?( str )
MESSAGE_ID === str
end
MIME_ENCODED = /=\?[^\s?=]+\?[QB]\?[^\s?=]+\?=/i
def mime_encoded?( str )
MIME_ENCODED === str
end
def decode_params( hash )
new = Hash.new
encoded = nil
hash.each do |key, value|
if m = /\*(?:(\d+)\*)?\z/.match(key)
((encoded ||= {})[m.pre_match] ||= [])[(m[1] || 0).to_i] = value
else
new[key] = to_kcode(value)
end
end
if encoded
encoded.each do |key, strings|
new[key] = decode_RFC2231(strings.join(''))
end
end
new
end
NKF_FLAGS = {
'EUC' => '-e -m',
'SJIS' => '-s -m'
}
def to_kcode( str )
flag = NKF_FLAGS[TMail.KCODE] or return str
NKF.nkf(flag, str)
end
RFC2231_ENCODED = /\A(?:iso-2022-jp|euc-jp|shift_jis|us-ascii)?'[a-z]*'/in
def decode_RFC2231( str )
m = RFC2231_ENCODED.match(str) or return str
begin
to_kcode(m.post_match.gsub(/%[\da-f]{2}/in) {|s| s[1,2].hex.chr })
rescue
m.post_match.gsub(/%[\da-f]{2}/in, "")
end
end
def quote_boundary
# Make sure the Content-Type boundary= parameter is quoted if it contains illegal characters
# (to ensure any special characters in the boundary text are escaped from the parser
# (such as = in MS Outlook's boundary text))
if @body =~ /^(.*)boundary=(.*)$/m
preamble = $1
remainder = $2
if remainder =~ /;/
remainder =~ /^(.*?)(;.*)$/m
boundary_text = $1
post = $2.chomp
else
boundary_text = remainder.chomp
end
if boundary_text =~ /[\/\?\=]/
boundary_text = "\"#{boundary_text}\"" unless boundary_text =~ /^".*?"$/
@body = "#{preamble}boundary=#{boundary_text}#{post}"
end
end
end
#:startdoc:
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb | #:stopdoc:
require 'tmail/mailbox'
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb | #:stopdoc:
# DO NOT MODIFY!!!!
# This file is automatically generated by racc 1.4.5
# from racc grammer file "parser.y".
#
#
# parser.rb: generated by racc (runtime embedded)
#
###### racc/parser.rb begin
unless $".index 'racc/parser.rb'
$".push 'racc/parser.rb'
self.class.module_eval <<'..end racc/parser.rb modeval..id8076474214', 'racc/parser.rb', 1
#
# $Id: parser.rb,v 1.7 2005/11/20 17:31:32 aamine Exp $
#
# Copyright (c) 1999-2005 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# As a special exception, when this code is copied by Racc
# into a Racc output file, you may use that output file
# without restriction.
#
unless defined?(NotImplementedError)
NotImplementedError = NotImplementError
end
module Racc
class ParseError < StandardError; end
end
unless defined?(::ParseError)
ParseError = Racc::ParseError
end
module Racc
unless defined?(Racc_No_Extentions)
Racc_No_Extentions = false
end
class Parser
Racc_Runtime_Version = '1.4.5'
Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1]
Racc_Runtime_Core_Version_R = '1.4.5'
Racc_Runtime_Core_Revision_R = '$Revision: 1.7 $'.split[1]
begin
require 'racc/cparse'
# Racc_Runtime_Core_Version_C = (defined in extention)
Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
unless new.respond_to?(:_racc_do_parse_c, true)
raise LoadError, 'old cparse.so'
end
if Racc_No_Extentions
raise LoadError, 'selecting ruby version of racc runtime core'
end
Racc_Main_Parsing_Routine = :_racc_do_parse_c
Racc_YY_Parse_Method = :_racc_yyparse_c
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
Racc_Runtime_Type = 'c'
rescue LoadError
Racc_Main_Parsing_Routine = :_racc_do_parse_rb
Racc_YY_Parse_Method = :_racc_yyparse_rb
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
Racc_Runtime_Type = 'ruby'
end
def Parser.racc_runtime_type
Racc_Runtime_Type
end
private
def _racc_setup
@yydebug = false unless self.class::Racc_debug_parser
@yydebug = false unless defined?(@yydebug)
if @yydebug
@racc_debug_out = $stderr unless defined?(@racc_debug_out)
@racc_debug_out ||= $stderr
end
arg = self.class::Racc_arg
arg[13] = true if arg.size < 14
arg
end
def _racc_init_sysvars
@racc_state = [0]
@racc_tstack = []
@racc_vstack = []
@racc_t = nil
@racc_val = nil
@racc_read_next = true
@racc_user_yyerror = false
@racc_error_status = 0
end
###
### do_parse
###
def do_parse
__send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
end
def next_token
raise NotImplementedError, "#{self.class}\#next_token is not defined"
end
def _racc_do_parse_rb(arg, in_debug)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
_racc_init_sysvars
tok = act = i = nil
nerr = 0
catch(:racc_end_parse) {
while true
if i = action_pointer[@racc_state[-1]]
if @racc_read_next
if @racc_t != 0 # not EOF
tok, @racc_val = next_token()
unless tok # EOF
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
racc_read_token(@racc_t, tok, @racc_val) if @yydebug
@racc_read_next = false
end
end
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
else
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
}
end
###
### yyparse
###
def yyparse(recv, mid)
__send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
end
def _racc_yyparse_rb(recv, mid, arg, c_debug)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
_racc_init_sysvars
tok = nil
act = nil
i = nil
nerr = 0
catch(:racc_end_parse) {
until i = action_pointer[@racc_state[-1]]
while act = _racc_evalact(action_default[@racc_state[-1]], arg)
;
end
end
recv.__send__(mid) do |tok, val|
unless tok
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
@racc_val = val
@racc_read_next = false
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
while not (i = action_pointer[@racc_state[-1]]) or
not @racc_read_next or
@racc_t == 0 # $
unless i and i += @racc_t and
i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
end
}
end
###
### common
###
def _racc_evalact(act, arg)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
nerr = 0 # tmp
if act > 0 and act < shift_n
#
# shift
#
if @racc_error_status > 0
@racc_error_status -= 1 unless @racc_t == 1 # error token
end
@racc_vstack.push @racc_val
@racc_state.push act
@racc_read_next = true
if @yydebug
@racc_tstack.push @racc_t
racc_shift @racc_t, @racc_tstack, @racc_vstack
end
elsif act < 0 and act > -reduce_n
#
# reduce
#
code = catch(:racc_jump) {
@racc_state.push _racc_do_reduce(arg, act)
false
}
if code
case code
when 1 # yyerror
@racc_user_yyerror = true # user_yyerror
return -reduce_n
when 2 # yyaccept
return shift_n
else
raise '[Racc Bug] unknown jump code'
end
end
elsif act == shift_n
#
# accept
#
racc_accept if @yydebug
throw :racc_end_parse, @racc_vstack[0]
elsif act == -reduce_n
#
# error
#
case @racc_error_status
when 0
unless arg[21] # user_yyerror
nerr += 1
on_error @racc_t, @racc_val, @racc_vstack
end
when 3
if @racc_t == 0 # is $
throw :racc_end_parse, nil
end
@racc_read_next = true
end
@racc_user_yyerror = false
@racc_error_status = 3
while true
if i = action_pointer[@racc_state[-1]]
i += 1 # error token
if i >= 0 and
(act = action_table[i]) and
action_check[i] == @racc_state[-1]
break
end
end
throw :racc_end_parse, nil if @racc_state.size <= 1
@racc_state.pop
@racc_vstack.pop
if @yydebug
@racc_tstack.pop
racc_e_pop @racc_state, @racc_tstack, @racc_vstack
end
end
return act
else
raise "[Racc Bug] unknown action #{act.inspect}"
end
racc_next_state(@racc_state[-1], @racc_state) if @yydebug
nil
end
def _racc_do_reduce(arg, act)
action_table, action_check, action_default, action_pointer,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, token_table, shift_n,
reduce_n, use_result, * = arg
state = @racc_state
vstack = @racc_vstack
tstack = @racc_tstack
i = act * -3
len = reduce_table[i]
reduce_to = reduce_table[i+1]
method_id = reduce_table[i+2]
void_array = []
tmp_t = tstack[-len, len] if @yydebug
tmp_v = vstack[-len, len]
tstack[-len, len] = void_array if @yydebug
vstack[-len, len] = void_array
state[-len, len] = void_array
# tstack must be updated AFTER method call
if use_result
vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
else
vstack.push __send__(method_id, tmp_v, vstack)
end
tstack.push reduce_to
racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
k1 = reduce_to - nt_base
if i = goto_pointer[k1]
i += state[-1]
if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
return curstate
end
end
goto_default[k1]
end
def on_error(t, val, vstack)
raise ParseError, sprintf("\nparse error on value %s (%s)",
val.inspect, token_to_str(t) || '?')
end
def yyerror
throw :racc_jump, 1
end
def yyaccept
throw :racc_jump, 2
end
def yyerrok
@racc_error_status = 0
end
#
# for debugging output
#
def racc_read_token(t, tok, val)
@racc_debug_out.print 'read '
@racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
@racc_debug_out.puts val.inspect
@racc_debug_out.puts
end
def racc_shift(tok, tstack, vstack)
@racc_debug_out.puts "shift #{racc_token2str tok}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_reduce(toks, sim, tstack, vstack)
out = @racc_debug_out
out.print 'reduce '
if toks.empty?
out.print ' <none>'
else
toks.each {|t| out.print ' ', racc_token2str(t) }
end
out.puts " --> #{racc_token2str(sim)}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_accept
@racc_debug_out.puts 'accept'
@racc_debug_out.puts
end
def racc_e_pop(state, tstack, vstack)
@racc_debug_out.puts 'error recovering mode: pop token'
racc_print_states state
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_next_state(curstate, state)
@racc_debug_out.puts "goto #{curstate}"
racc_print_states state
@racc_debug_out.puts
end
def racc_print_stacks(t, v)
out = @racc_debug_out
out.print ' ['
t.each_index do |i|
out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
end
out.puts ' ]'
end
def racc_print_states(s)
out = @racc_debug_out
out.print ' ['
s.each {|st| out.print ' ', st }
out.puts ' ]'
end
def racc_token2str(tok)
self.class::Racc_token_to_s_table[tok] or
raise "[Racc Bug] can't convert token #{tok} to string"
end
def token_to_str(t)
self.class::Racc_token_to_s_table[t]
end
end
end
..end racc/parser.rb modeval..id8076474214
end
###### racc/parser.rb end
#
# parser.rb
#
# Copyright (c) 1998-2007 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2.1.
#
require 'tmail/scanner'
require 'tmail/utils'
module TMail
class Parser < Racc::Parser
module_eval <<'..end parser.y modeval..id7b0b3dccb7', 'parser.y', 340
include TextUtils
def self.parse( ident, str, cmt = nil )
new.parse(ident, str, cmt)
end
MAILP_DEBUG = false
def initialize
self.debug = MAILP_DEBUG
end
def debug=( flag )
@yydebug = flag && Racc_debug_parser
@scanner_debug = flag
end
def debug
@yydebug
end
def parse( ident, str, comments = nil )
@scanner = Scanner.new(str, ident, comments)
@scanner.debug = @scanner_debug
@first = [ident, ident]
result = yyparse(self, :parse_in)
comments.map! {|c| to_kcode(c) } if comments
result
end
private
def parse_in( &block )
yield @first
@scanner.scan(&block)
end
def on_error( t, val, vstack )
raise SyntaxError, "parse error on token #{racc_token2str t}"
end
..end parser.y modeval..id7b0b3dccb7
##### racc 1.4.5 generates ###
racc_reduce_table = [
0, 0, :racc_error,
2, 35, :_reduce_1,
2, 35, :_reduce_2,
2, 35, :_reduce_3,
2, 35, :_reduce_4,
2, 35, :_reduce_5,
2, 35, :_reduce_6,
2, 35, :_reduce_7,
2, 35, :_reduce_8,
2, 35, :_reduce_9,
2, 35, :_reduce_10,
2, 35, :_reduce_11,
2, 35, :_reduce_12,
6, 36, :_reduce_13,
0, 48, :_reduce_none,
2, 48, :_reduce_none,
3, 49, :_reduce_16,
5, 49, :_reduce_17,
1, 50, :_reduce_18,
7, 37, :_reduce_19,
0, 51, :_reduce_none,
2, 51, :_reduce_21,
0, 52, :_reduce_none,
2, 52, :_reduce_23,
1, 58, :_reduce_24,
3, 58, :_reduce_25,
2, 58, :_reduce_26,
0, 53, :_reduce_none,
2, 53, :_reduce_28,
0, 54, :_reduce_29,
3, 54, :_reduce_30,
0, 55, :_reduce_none,
2, 55, :_reduce_32,
2, 55, :_reduce_33,
0, 56, :_reduce_none,
2, 56, :_reduce_35,
1, 61, :_reduce_36,
1, 61, :_reduce_37,
0, 57, :_reduce_none,
2, 57, :_reduce_39,
1, 38, :_reduce_none,
1, 38, :_reduce_none,
3, 38, :_reduce_none,
1, 46, :_reduce_none,
1, 46, :_reduce_none,
1, 46, :_reduce_none,
1, 39, :_reduce_none,
2, 39, :_reduce_47,
1, 64, :_reduce_48,
3, 64, :_reduce_49,
1, 68, :_reduce_none,
1, 68, :_reduce_none,
1, 69, :_reduce_52,
3, 69, :_reduce_53,
1, 47, :_reduce_none,
1, 47, :_reduce_none,
2, 47, :_reduce_56,
2, 67, :_reduce_none,
3, 65, :_reduce_58,
2, 65, :_reduce_59,
1, 70, :_reduce_60,
2, 70, :_reduce_61,
4, 62, :_reduce_62,
3, 62, :_reduce_63,
2, 72, :_reduce_none,
2, 73, :_reduce_65,
4, 73, :_reduce_66,
3, 63, :_reduce_67,
1, 63, :_reduce_68,
1, 74, :_reduce_none,
2, 74, :_reduce_70,
1, 71, :_reduce_71,
3, 71, :_reduce_72,
1, 59, :_reduce_73,
3, 59, :_reduce_74,
1, 76, :_reduce_75,
2, 76, :_reduce_76,
1, 75, :_reduce_none,
1, 75, :_reduce_none,
1, 75, :_reduce_none,
1, 77, :_reduce_none,
1, 77, :_reduce_none,
1, 77, :_reduce_none,
1, 66, :_reduce_none,
2, 66, :_reduce_none,
3, 60, :_reduce_85,
1, 40, :_reduce_86,
3, 40, :_reduce_87,
1, 79, :_reduce_none,
2, 79, :_reduce_89,
1, 41, :_reduce_90,
2, 41, :_reduce_91,
3, 42, :_reduce_92,
5, 43, :_reduce_93,
3, 43, :_reduce_94,
0, 80, :_reduce_95,
5, 80, :_reduce_96,
5, 80, :_reduce_97,
1, 44, :_reduce_98,
3, 45, :_reduce_99,
0, 81, :_reduce_none,
1, 81, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none,
1, 78, :_reduce_none ]
racc_reduce_n = 109
racc_shift_n = 167
racc_action_table = [
-70, -69, 23, 25, 145, 146, 29, 31, 105, 106,
16, 17, 20, 22, 136, 27, -70, -69, 32, 101,
-70, -69, 153, 100, 113, 115, -70, -69, -70, 109,
75, 23, 25, 101, 154, 29, 31, 142, 143, 16,
17, 20, 22, 107, 27, 23, 25, 32, 98, 29,
31, 96, 94, 16, 17, 20, 22, 78, 27, 23,
25, 32, 112, 29, 31, 74, 91, 16, 17, 20,
22, 88, 117, 92, 81, 32, 23, 25, 80, 123,
29, 31, 100, 125, 16, 17, 20, 22, 126, 23,
25, 109, 32, 29, 31, 91, 128, 16, 17, 20,
22, 129, 27, 23, 25, 32, 101, 29, 31, 101,
130, 16, 17, 20, 22, 79, 52, 23, 25, 32,
78, 29, 31, 133, 78, 16, 17, 20, 22, 77,
23, 25, 75, 32, 29, 31, 65, 62, 16, 17,
20, 22, 139, 23, 25, 101, 32, 29, 31, 60,
100, 16, 17, 20, 22, 44, 27, 101, 147, 32,
23, 25, 120, 148, 29, 31, 151, 152, 16, 17,
20, 22, 42, 27, 156, 158, 32, 23, 25, 120,
40, 29, 31, 15, 163, 16, 17, 20, 22, 40,
27, 23, 25, 32, 68, 29, 31, 165, 166, 16,
17, 20, 22, nil, 27, 23, 25, 32, nil, 29,
31, 74, nil, 16, 17, 20, 22, nil, 23, 25,
nil, 32, 29, 31, nil, nil, 16, 17, 20, 22,
nil, 23, 25, nil, 32, 29, 31, nil, nil, 16,
17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
27, 23, 25, 32, nil, 29, 31, nil, nil, 16,
17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
84, 25, nil, 32, 29, 31, nil, 87, 16, 17,
20, 22, 4, 6, 7, 8, 9, 10, 11, 12,
13, 1, 2, 3, 84, 25, nil, nil, 29, 31,
nil, 87, 16, 17, 20, 22, 84, 25, nil, nil,
29, 31, nil, 87, 16, 17, 20, 22, 84, 25,
nil, nil, 29, 31, nil, 87, 16, 17, 20, 22,
84, 25, nil, nil, 29, 31, nil, 87, 16, 17,
20, 22, 84, 25, nil, nil, 29, 31, nil, 87,
16, 17, 20, 22, 84, 25, nil, nil, 29, 31,
nil, 87, 16, 17, 20, 22 ]
racc_action_check = [
75, 28, 68, 68, 136, 136, 68, 68, 72, 72,
68, 68, 68, 68, 126, 68, 75, 28, 68, 67,
75, 28, 143, 66, 86, 86, 75, 28, 75, 75,
28, 3, 3, 86, 143, 3, 3, 134, 134, 3,
3, 3, 3, 73, 3, 151, 151, 3, 62, 151,
151, 60, 56, 151, 151, 151, 151, 51, 151, 52,
52, 151, 80, 52, 52, 52, 50, 52, 52, 52,
52, 45, 89, 52, 42, 52, 71, 71, 41, 96,
71, 71, 97, 98, 71, 71, 71, 71, 100, 7,
7, 101, 71, 7, 7, 102, 104, 7, 7, 7,
7, 105, 7, 8, 8, 7, 108, 8, 8, 111,
112, 8, 8, 8, 8, 40, 8, 9, 9, 8,
36, 9, 9, 117, 121, 9, 9, 9, 9, 33,
10, 10, 70, 9, 10, 10, 13, 12, 10, 10,
10, 10, 130, 2, 2, 131, 10, 2, 2, 11,
135, 2, 2, 2, 2, 6, 2, 138, 139, 2,
90, 90, 90, 140, 90, 90, 141, 142, 90, 90,
90, 90, 5, 90, 147, 150, 90, 127, 127, 127,
4, 127, 127, 1, 156, 127, 127, 127, 127, 158,
127, 26, 26, 127, 26, 26, 26, 162, 163, 26,
26, 26, 26, nil, 26, 27, 27, 26, nil, 27,
27, 27, nil, 27, 27, 27, 27, nil, 154, 154,
nil, 27, 154, 154, nil, nil, 154, 154, 154, 154,
nil, 122, 122, nil, 154, 122, 122, nil, nil, 122,
122, 122, 122, nil, 76, 76, nil, 122, 76, 76,
nil, nil, 76, 76, 76, 76, nil, 38, 38, nil,
76, 38, 38, nil, nil, 38, 38, 38, 38, nil,
38, 55, 55, 38, nil, 55, 55, nil, nil, 55,
55, 55, 55, nil, 94, 94, nil, 55, 94, 94,
nil, nil, 94, 94, 94, 94, nil, 59, 59, nil,
94, 59, 59, nil, nil, 59, 59, 59, 59, nil,
114, 114, nil, 59, 114, 114, nil, 114, 114, 114,
114, 114, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 77, 77, nil, nil, 77, 77,
nil, 77, 77, 77, 77, 77, 44, 44, nil, nil,
44, 44, nil, 44, 44, 44, 44, 44, 113, 113,
nil, nil, 113, 113, nil, 113, 113, 113, 113, 113,
88, 88, nil, nil, 88, 88, nil, 88, 88, 88,
88, 88, 74, 74, nil, nil, 74, 74, nil, 74,
74, 74, 74, 74, 129, 129, nil, nil, 129, 129,
nil, 129, 129, 129, 129, 129 ]
racc_action_pointer = [
320, 152, 129, 17, 165, 172, 137, 75, 89, 103,
116, 135, 106, 105, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, 177, 191, 1, nil,
nil, nil, nil, 109, nil, nil, 94, nil, 243, nil,
99, 64, 74, nil, 332, 52, nil, nil, nil, nil,
50, 31, 45, nil, nil, 257, 36, nil, nil, 283,
22, nil, 16, nil, nil, nil, -3, -10, -12, nil,
103, 62, -8, 15, 368, 0, 230, 320, nil, nil,
47, nil, nil, nil, nil, nil, 4, nil, 356, 50,
146, nil, nil, nil, 270, nil, 65, 56, 52, nil,
57, 62, 79, nil, 68, 81, nil, nil, 77, nil,
nil, 80, 96, 344, 296, nil, nil, 108, nil, nil,
nil, 98, 217, nil, nil, nil, -19, 163, nil, 380,
128, 116, nil, nil, 14, 124, -26, nil, 128, 141,
148, 141, 152, 7, nil, nil, nil, 160, nil, nil,
149, 31, nil, nil, 204, nil, 167, nil, 174, nil,
nil, nil, 169, 184, nil, nil, nil ]
racc_action_default = [
-109, -109, -109, -109, -14, -109, -20, -109, -109, -109,
-109, -109, -109, -109, -10, -95, -105, -106, -77, -44,
-107, -11, -108, -79, -43, -102, -109, -109, -60, -103,
-55, -104, -78, -68, -54, -71, -45, -12, -109, -1,
-109, -109, -109, -2, -109, -22, -51, -48, -50, -3,
-40, -41, -109, -46, -4, -86, -5, -88, -6, -90,
-109, -7, -95, -8, -9, -98, -100, -61, -59, -56,
-69, -109, -109, -109, -109, -75, -109, -109, -57, -15,
-109, 167, -73, -80, -82, -21, -24, -81, -109, -27,
-109, -83, -47, -89, -109, -91, -109, -100, -109, -99,
-101, -75, -58, -52, -109, -109, -64, -63, -65, -76,
-72, -67, -109, -109, -109, -26, -23, -109, -29, -49,
-84, -42, -87, -92, -94, -95, -109, -109, -62, -109,
-109, -25, -74, -28, -31, -100, -109, -53, -66, -109,
-109, -34, -109, -109, -93, -96, -97, -109, -18, -13,
-38, -109, -30, -33, -109, -32, -16, -19, -14, -35,
-36, -37, -109, -109, -39, -85, -17 ]
racc_goto_table = [
39, 67, 70, 73, 38, 66, 69, 24, 37, 57,
59, 36, 55, 67, 99, 90, 85, 157, 69, 108,
83, 134, 111, 76, 49, 53, 141, 70, 73, 150,
118, 89, 45, 155, 159, 149, 140, 21, 14, 19,
119, 102, 64, 63, 61, 124, 70, 104, 58, 132,
83, 56, 97, 83, 54, 93, 43, 5, 131, 95,
116, nil, 76, nil, 83, 76, nil, 127, nil, 38,
nil, nil, nil, 103, 138, nil, 110, nil, nil, nil,
nil, nil, nil, 144, nil, nil, nil, nil, nil, 83,
83, nil, nil, nil, 57, nil, nil, 122, nil, 121,
nil, nil, nil, nil, nil, 83, nil, nil, nil, nil,
nil, nil, nil, nil, nil, 135, nil, nil, nil, nil,
nil, nil, 93, nil, nil, nil, 70, 161, 38, 70,
162, 160, 137, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 164 ]
racc_goto_check = [
2, 37, 37, 29, 36, 46, 28, 13, 13, 41,
41, 31, 45, 37, 47, 32, 24, 23, 28, 25,
44, 20, 25, 42, 4, 4, 21, 37, 29, 22,
19, 18, 17, 26, 27, 16, 15, 12, 11, 33,
34, 35, 10, 9, 8, 47, 37, 29, 7, 43,
44, 6, 46, 44, 5, 41, 3, 1, 25, 41,
24, nil, 42, nil, 44, 42, nil, 32, nil, 36,
nil, nil, nil, 13, 25, nil, 41, nil, nil, nil,
nil, nil, nil, 47, nil, nil, nil, nil, nil, 44,
44, nil, nil, nil, 41, nil, nil, 45, nil, 31,
nil, nil, nil, nil, nil, 44, nil, nil, nil, nil,
nil, nil, nil, nil, nil, 46, nil, nil, nil, nil,
nil, nil, 41, nil, nil, nil, 37, 29, 36, 37,
29, 28, 13, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 2 ]
racc_goto_pointer = [
nil, 57, -4, 50, 17, 46, 42, 38, 33, 31,
29, 37, 35, 5, nil, -94, -105, 26, -14, -59,
-97, -108, -112, -133, -28, -55, -110, -117, -20, -24,
nil, 9, -35, 37, -50, -27, 1, -25, nil, nil,
nil, 0, -5, -65, -24, 3, -10, -52 ]
racc_goto_default = [
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, 48, 41, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, 86, nil, nil, 30, 34,
50, 51, nil, 46, 47, nil, 26, 28, 71, 72,
33, 35, 114, 82, 18, nil, nil, nil ]
racc_token_table = {
false => 0,
Object.new => 1,
:DATETIME => 2,
:RECEIVED => 3,
:MADDRESS => 4,
:RETPATH => 5,
:KEYWORDS => 6,
:ENCRYPTED => 7,
:MIMEVERSION => 8,
:CTYPE => 9,
:CENCODING => 10,
:CDISPOSITION => 11,
:ADDRESS => 12,
:MAILBOX => 13,
:DIGIT => 14,
:ATOM => 15,
"," => 16,
":" => 17,
:FROM => 18,
:BY => 19,
"@" => 20,
:DOMLIT => 21,
:VIA => 22,
:WITH => 23,
:ID => 24,
:FOR => 25,
";" => 26,
"<" => 27,
">" => 28,
"." => 29,
:QUOTED => 30,
:TOKEN => 31,
"/" => 32,
"=" => 33 }
racc_use_result_var = false
racc_nt_base = 34
Racc_arg = [
racc_action_table,
racc_action_check,
racc_action_default,
racc_action_pointer,
racc_goto_table,
racc_goto_check,
racc_goto_default,
racc_goto_pointer,
racc_nt_base,
racc_reduce_table,
racc_token_table,
racc_shift_n,
racc_reduce_n,
racc_use_result_var ]
Racc_token_to_s_table = [
'$end',
'error',
'DATETIME',
'RECEIVED',
'MADDRESS',
'RETPATH',
'KEYWORDS',
'ENCRYPTED',
'MIMEVERSION',
'CTYPE',
'CENCODING',
'CDISPOSITION',
'ADDRESS',
'MAILBOX',
'DIGIT',
'ATOM',
'","',
'":"',
'FROM',
'BY',
'"@"',
'DOMLIT',
'VIA',
'WITH',
'ID',
'FOR',
'";"',
'"<"',
'">"',
'"."',
'QUOTED',
'TOKEN',
'"/"',
'"="',
'$start',
'content',
'datetime',
'received',
'addrs_TOP',
'retpath',
'keys',
'enc',
'version',
'ctype',
'cencode',
'cdisp',
'addr_TOP',
'mbox',
'day',
'hour',
'zone',
'from',
'by',
'via',
'with',
'id',
'for',
'received_datetime',
'received_domain',
'domain',
'msgid',
'received_addrspec',
'routeaddr',
'spec',
'addrs',
'group_bare',
'commas',
'group',
'addr',
'mboxes',
'addr_phrase',
'local_head',
'routes',
'at_domains',
'local',
'word',
'dots',
'domword',
'atom',
'phrase',
'params',
'opt_semicolon']
Racc_debug_parser = false
##### racc system variables end #####
# reduce 0 omitted
module_eval <<'.,.,', 'parser.y', 16
def _reduce_1( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 17
def _reduce_2( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 18
def _reduce_3( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 19
def _reduce_4( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 20
def _reduce_5( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 21
def _reduce_6( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 22
def _reduce_7( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 23
def _reduce_8( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 24
def _reduce_9( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 25
def _reduce_10( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 26
def _reduce_11( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 27
def _reduce_12( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 36
def _reduce_13( val, _values)
t = Time.gm(val[3].to_i, val[2], val[1].to_i, 0, 0, 0)
(t + val[4] - val[5]).localtime
end
.,.,
# reduce 14 omitted
# reduce 15 omitted
module_eval <<'.,.,', 'parser.y', 45
def _reduce_16( val, _values)
(val[0].to_i * 60 * 60) +
(val[2].to_i * 60)
end
.,.,
module_eval <<'.,.,', 'parser.y', 51
def _reduce_17( val, _values)
(val[0].to_i * 60 * 60) +
(val[2].to_i * 60) +
(val[4].to_i)
end
.,.,
module_eval <<'.,.,', 'parser.y', 56
def _reduce_18( val, _values)
timezone_string_to_unixtime(val[0])
end
.,.,
module_eval <<'.,.,', 'parser.y', 61
def _reduce_19( val, _values)
val
end
.,.,
# reduce 20 omitted
module_eval <<'.,.,', 'parser.y', 67
def _reduce_21( val, _values)
val[1]
end
.,.,
# reduce 22 omitted
module_eval <<'.,.,', 'parser.y', 73
def _reduce_23( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 79
def _reduce_24( val, _values)
join_domain(val[0])
end
.,.,
module_eval <<'.,.,', 'parser.y', 83
def _reduce_25( val, _values)
join_domain(val[2])
end
.,.,
module_eval <<'.,.,', 'parser.y', 87
def _reduce_26( val, _values)
join_domain(val[0])
end
.,.,
# reduce 27 omitted
module_eval <<'.,.,', 'parser.y', 93
def _reduce_28( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 98
def _reduce_29( val, _values)
[]
end
.,.,
module_eval <<'.,.,', 'parser.y', 103
def _reduce_30( val, _values)
val[0].push val[2]
val[0]
end
.,.,
# reduce 31 omitted
module_eval <<'.,.,', 'parser.y', 109
def _reduce_32( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 113
def _reduce_33( val, _values)
val[1]
end
.,.,
# reduce 34 omitted
module_eval <<'.,.,', 'parser.y', 119
def _reduce_35( val, _values)
val[1]
end
.,.,
module_eval <<'.,.,', 'parser.y', 125
def _reduce_36( val, _values)
val[0].spec
end
.,.,
module_eval <<'.,.,', 'parser.y', 129
def _reduce_37( val, _values)
val[0].spec
end
.,.,
# reduce 38 omitted
module_eval <<'.,.,', 'parser.y', 136
def _reduce_39( val, _values)
val[1]
end
.,.,
# reduce 40 omitted
# reduce 41 omitted
# reduce 42 omitted
# reduce 43 omitted
# reduce 44 omitted
# reduce 45 omitted
# reduce 46 omitted
module_eval <<'.,.,', 'parser.y', 146
def _reduce_47( val, _values)
[ Address.new(nil, nil) ]
end
.,.,
module_eval <<'.,.,', 'parser.y', 152
def _reduce_48( val, _values)
val
end
.,.,
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb | #:stopdoc:
unless Enumerable.method_defined?(:map)
module Enumerable #:nodoc:
alias map collect
end
end
unless Enumerable.method_defined?(:select)
module Enumerable #:nodoc:
alias select find_all
end
end
unless Enumerable.method_defined?(:reject)
module Enumerable #:nodoc:
def reject
result = []
each do |i|
result.push i unless yield(i)
end
result
end
end
end
unless Enumerable.method_defined?(:sort_by)
module Enumerable #:nodoc:
def sort_by
map {|i| [yield(i), i] }.sort.map {|val, i| i }
end
end
end
unless File.respond_to?(:read)
def File.read(fname) #:nodoc:
File.open(fname) {|f|
return f.read
}
end
end
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb | =begin rdoc
= Address handling class
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
require 'tmail/encode'
require 'tmail/parser'
module TMail
# = Class Address
#
# Provides a complete handling library for email addresses. Can parse a string of an
# address directly or take in preformatted addresses themselves. Allows you to add
# and remove phrases from the front of the address and provides a compare function for
# email addresses.
#
# == Parsing and Handling a Valid Address:
#
# Just pass the email address in as a string to Address.parse:
#
# email = TMail::Address.parse('Mikel Lindsaar <mikel@lindsaar.net>)
# #=> #<TMail::Address mikel@lindsaar.net>
# email.address
# #=> "mikel@lindsaar.net"
# email.local
# #=> "mikel"
# email.domain
# #=> "lindsaar.net"
# email.name # Aliased as phrase as well
# #=> "Mikel Lindsaar"
#
# == Detecting an Invalid Address
#
# If you want to check the syntactical validity of an email address, just pass it to
# Address.parse and catch any SyntaxError:
#
# begin
# TMail::Mail.parse("mikel 2@@@@@ me .com")
# rescue TMail::SyntaxError
# puts("Invalid Email Address Detected")
# else
# puts("Address is valid")
# end
# #=> "Invalid Email Address Detected"
class Address
include TextUtils #:nodoc:
# Sometimes you need to parse an address, TMail can do it for you and provide you with
# a fairly robust method of detecting a valid address.
#
# Takes in a string, returns a TMail::Address object.
#
# Raises a TMail::SyntaxError on invalid email format
def Address.parse( str )
Parser.parse :ADDRESS, special_quote_address(str)
end
def Address.special_quote_address(str) #:nodoc:
# Takes a string which is an address and adds quotation marks to special
# edge case methods that the RACC parser can not handle.
#
# Right now just handles two edge cases:
#
# Full stop as the last character of the display name:
# Mikel L. <mikel@me.com>
# Returns:
# "Mikel L." <mikel@me.com>
#
# Unquoted @ symbol in the display name:
# mikel@me.com <mikel@me.com>
# Returns:
# "mikel@me.com" <mikel@me.com>
#
# Any other address not matching these patterns just gets returned as is.
case
# This handles the missing "" in an older version of Apple Mail.app
# around the display name when the display name contains a '@'
# like 'mikel@me.com <mikel@me.com>'
# Just quotes it to: '"mikel@me.com" <mikel@me.com>'
when str =~ /\A([^"].+@.+[^"])\s(<.*?>)\Z/
return "\"#{$1}\" #{$2}"
# This handles cases where 'Mikel A. <mikel@me.com>' which is a trailing
# full stop before the address section. Just quotes it to
# '"Mikel A. <mikel@me.com>"
when str =~ /\A(.*?\.)\s(<.*?>)\Z/
return "\"#{$1}\" #{$2}"
else
str
end
end
def address_group? #:nodoc:
false
end
# Address.new(local, domain)
#
# Accepts:
#
# * local - Left of the at symbol
#
# * domain - Array of the domain split at the periods.
#
# For example:
#
# Address.new("mikel", ["lindsaar", "net"])
# #=> "#<TMail::Address mikel@lindsaar.net>"
def initialize( local, domain )
if domain
domain.each do |s|
raise SyntaxError, 'empty word in domain' if s.empty?
end
end
# This is to catch an unquoted "@" symbol in the local part of the
# address. Handles addresses like <"@"@me.com> and makes sure they
# stay like <"@"@me.com> (previously were becoming <@@me.com>)
if local && (local.join == '@' || local.join =~ /\A[^"].*?@.*?[^"]\Z/)
@local = "\"#{local.join}\""
else
@local = local
end
@domain = domain
@name = nil
@routes = []
end
# Provides the name or 'phrase' of the email address.
#
# For Example:
#
# email = TMail::Address.parse("Mikel Lindsaar <mikel@lindsaar.net>")
# email.name
# #=> "Mikel Lindsaar"
def name
@name
end
# Setter method for the name or phrase of the email
#
# For Example:
#
# email = TMail::Address.parse("mikel@lindsaar.net")
# email.name
# #=> nil
# email.name = "Mikel Lindsaar"
# email.to_s
# #=> "Mikel Lindsaar <mikel@me.com>"
def name=( str )
@name = str
@name = nil if str and str.empty?
end
#:stopdoc:
alias phrase name
alias phrase= name=
#:startdoc:
# This is still here from RFC 822, and is now obsolete per RFC2822 Section 4.
#
# "When interpreting addresses, the route portion SHOULD be ignored."
#
# It is still here, so you can access it.
#
# Routes return the route portion at the front of the email address, if any.
#
# For Example:
# email = TMail::Address.parse( "<@sa,@another:Mikel@me.com>")
# => #<TMail::Address Mikel@me.com>
# email.to_s
# => "<@sa,@another:Mikel@me.com>"
# email.routes
# => ["sa", "another"]
def routes
@routes
end
def inspect #:nodoc:
"#<#{self.class} #{address()}>"
end
# Returns the local part of the email address
#
# For Example:
#
# email = TMail::Address.parse("mikel@lindsaar.net")
# email.local
# #=> "mikel"
def local
return nil unless @local
return '""' if @local.size == 1 and @local[0].empty?
# Check to see if it is an array before trying to map it
if @local.respond_to?(:map)
@local.map {|i| quote_atom(i) }.join('.')
else
quote_atom(@local)
end
end
# Returns the domain part of the email address
#
# For Example:
#
# email = TMail::Address.parse("mikel@lindsaar.net")
# email.local
# #=> "lindsaar.net"
def domain
return nil unless @domain
join_domain(@domain)
end
# Returns the full specific address itself
#
# For Example:
#
# email = TMail::Address.parse("mikel@lindsaar.net")
# email.address
# #=> "mikel@lindsaar.net"
def spec
s = self.local
d = self.domain
if s and d
s + '@' + d
else
s
end
end
alias address spec
# Provides == function to the email. Only checks the actual address
# and ignores the name/phrase component
#
# For Example
#
# addr1 = TMail::Address.parse("My Address <mikel@lindsaar.net>")
# #=> "#<TMail::Address mikel@lindsaar.net>"
# addr2 = TMail::Address.parse("Another <mikel@lindsaar.net>")
# #=> "#<TMail::Address mikel@lindsaar.net>"
# addr1 == addr2
# #=> true
def ==( other )
other.respond_to? :spec and self.spec == other.spec
end
alias eql? ==
# Provides a unique hash value for this record against the local and domain
# parts, ignores the name/phrase value
#
# email = TMail::Address.parse("mikel@lindsaar.net")
# email.hash
# #=> 18767598
def hash
@local.hash ^ @domain.hash
end
# Duplicates a TMail::Address object returning the duplicate
#
# addr1 = TMail::Address.parse("mikel@lindsaar.net")
# addr2 = addr1.dup
# addr1.id == addr2.id
# #=> false
def dup
obj = self.class.new(@local.dup, @domain.dup)
obj.name = @name.dup if @name
obj.routes.replace @routes
obj
end
include StrategyInterface #:nodoc:
def accept( strategy, dummy1 = nil, dummy2 = nil ) #:nodoc:
unless @local
strategy.meta '<>' # empty return-path
return
end
spec_p = (not @name and @routes.empty?)
if @name
strategy.phrase @name
strategy.space
end
tmp = spec_p ? '' : '<'
unless @routes.empty?
tmp << @routes.map {|i| '@' + i }.join(',') << ':'
end
tmp << self.spec
tmp << '>' unless spec_p
strategy.meta tmp
strategy.lwsp ''
end
end
class AddressGroup
include Enumerable
def address_group?
true
end
def initialize( name, addrs )
@name = name
@addresses = addrs
end
attr_reader :name
def ==( other )
other.respond_to? :to_a and @addresses == other.to_a
end
alias eql? ==
def hash
map {|i| i.hash }.hash
end
def []( idx )
@addresses[idx]
end
def size
@addresses.size
end
def empty?
@addresses.empty?
end
def each( &block )
@addresses.each(&block)
end
def to_a
@addresses.dup
end
alias to_ary to_a
def include?( a )
@addresses.include? a
end
def flatten
set = []
@addresses.each do |a|
if a.respond_to? :flatten
set.concat a.flatten
else
set.push a
end
end
set
end
def each_address( &block )
flatten.each(&block)
end
def add( a )
@addresses.push a
end
alias push add
def delete( a )
@addresses.delete a
end
include StrategyInterface
def accept( strategy, dummy1 = nil, dummy2 = nil )
strategy.phrase @name
strategy.meta ':'
strategy.space
first = true
each do |mbox|
if first
first = false
else
strategy.meta ','
end
strategy.space
mbox.accept strategy
end
strategy.meta ';'
strategy.lwsp ''
end
end
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb | #--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
module TMail
module Base64
module_function
def folding_encode( str, eol = "\n", limit = 60 )
[str].pack('m')
end
def encode( str )
[str].pack('m').tr( "\r\n", '' )
end
def decode( str, strict = false )
str.unpack('m').first
end
end
end
#:startdoc:
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb | =begin rdoc
= Scanner for TMail
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
#require 'tmail/require_arch'
require 'tmail/utils'
require 'tmail/config'
module TMail
# NOTE: It woiuld be nice if these two libs could boith be called "tmailscanner", and
# the native extension would have precedence. However RubyGems boffs that up b/c
# it does not gaurantee load_path order.
begin
raise LoadError, 'Turned off native extentions by user choice' if ENV['NORUBYEXT']
require('tmail/tmailscanner') # c extension
Scanner = TMailScanner
rescue LoadError
require 'tmail/scanner_r'
Scanner = TMailScanner
end
end
#:stopdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb | =begin rdoc
= Mailbox and Mbox interaction class
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
require 'tmail/port'
require 'socket'
require 'mutex_m'
unless [].respond_to?(:sort_by)
module Enumerable#:nodoc:
def sort_by
map {|i| [yield(i), i] }.sort {|a,b| a.first <=> b.first }.map {|i| i[1] }
end
end
end
module TMail
class MhMailbox
PORT_CLASS = MhPort
def initialize( dir )
edir = File.expand_path(dir)
raise ArgumentError, "not directory: #{dir}"\
unless FileTest.directory? edir
@dirname = edir
@last_file = nil
@last_atime = nil
end
def directory
@dirname
end
alias dirname directory
attr_accessor :last_atime
def inspect
"#<#{self.class} #{@dirname}>"
end
def close
end
def new_port
PORT_CLASS.new(next_file_name())
end
def each_port
mail_files().each do |path|
yield PORT_CLASS.new(path)
end
@last_atime = Time.now
end
alias each each_port
def reverse_each_port
mail_files().reverse_each do |path|
yield PORT_CLASS.new(path)
end
@last_atime = Time.now
end
alias reverse_each reverse_each_port
# old #each_mail returns Port
#def each_mail
# each_port do |port|
# yield Mail.new(port)
# end
#end
def each_new_port( mtime = nil, &block )
mtime ||= @last_atime
return each_port(&block) unless mtime
return unless File.mtime(@dirname) >= mtime
mail_files().each do |path|
yield PORT_CLASS.new(path) if File.mtime(path) > mtime
end
@last_atime = Time.now
end
private
def mail_files
Dir.entries(@dirname)\
.select {|s| /\A\d+\z/ === s }\
.map {|s| s.to_i }\
.sort\
.map {|i| "#{@dirname}/#{i}" }\
.select {|path| FileTest.file? path }
end
def next_file_name
unless n = @last_file
n = 0
Dir.entries(@dirname)\
.select {|s| /\A\d+\z/ === s }\
.map {|s| s.to_i }.sort\
.each do |i|
next unless FileTest.file? "#{@dirname}/#{i}"
n = i
end
end
begin
n += 1
end while FileTest.exist? "#{@dirname}/#{n}"
@last_file = n
"#{@dirname}/#{n}"
end
end # MhMailbox
MhLoader = MhMailbox
class UNIXMbox
class << self
alias newobj new
end
# Creates a new mailbox object that you can iterate through to collect the
# emails from with "each_port".
#
# You need to pass it a filename of a unix mailbox format file, the format of this
# file can be researched at this page at {wikipedia}[link:http://en.wikipedia.org/wiki/Mbox]
#
# ==== Parameters
#
# +filename+: The filename of the mailbox you want to open
#
# +tmpdir+: Can be set to override TMail using the system environment's temp dir. TMail will first
# use the temp dir specified by you (if any) or then the temp dir specified in the Environment's TEMP
# value then the value in the Environment's TMP value or failing all of the above, '/tmp'
#
# +readonly+: If set to false, each email you take from the mail box will be removed from the mailbox.
# default is *false* - ie, it *WILL* truncate your mailbox file to ZERO once it has read the emails out.
#
# ==== Options:
#
# None
#
# ==== Examples:
#
# # First show using readonly true:
#
# require 'ftools'
# File.size("../test/fixtures/mailbox")
# #=> 20426
#
# mailbox = TMail::UNIXMbox.new("../test/fixtures/mailbox", nil, true)
# #=> #<TMail::UNIXMbox:0x14a2aa8 @readonly=true.....>
#
# mailbox.each_port do |port|
# mail = TMail::Mail.new(port)
# puts mail.subject
# end
# #Testing mailbox 1
# #Testing mailbox 2
# #Testing mailbox 3
# #Testing mailbox 4
# require 'ftools'
# File.size?("../test/fixtures/mailbox")
# #=> 20426
#
# # Now show with readonly set to the default false
#
# mailbox = TMail::UNIXMbox.new("../test/fixtures/mailbox")
# #=> #<TMail::UNIXMbox:0x14a2aa8 @readonly=false.....>
#
# mailbox.each_port do |port|
# mail = TMail::Mail.new(port)
# puts mail.subject
# end
# #Testing mailbox 1
# #Testing mailbox 2
# #Testing mailbox 3
# #Testing mailbox 4
#
# File.size?("../test/fixtures/mailbox")
# #=> nil
def UNIXMbox.new( filename, tmpdir = nil, readonly = false )
tmpdir = ENV['TEMP'] || ENV['TMP'] || '/tmp'
newobj(filename, "#{tmpdir}/ruby_tmail_#{$$}_#{rand()}", readonly, false)
end
def UNIXMbox.lock( fname )
begin
f = File.open(fname, 'r+')
f.flock File::LOCK_EX
yield f
ensure
f.flock File::LOCK_UN
f.close if f and not f.closed?
end
end
def UNIXMbox.static_new( fname, dir, readonly = false )
newobj(fname, dir, readonly, true)
end
def initialize( fname, mhdir, readonly, static )
@filename = fname
@readonly = readonly
@closed = false
Dir.mkdir mhdir
@real = MhMailbox.new(mhdir)
@finalizer = UNIXMbox.mkfinal(@real, @filename, !@readonly, !static)
ObjectSpace.define_finalizer self, @finalizer
end
def UNIXMbox.mkfinal( mh, mboxfile, writeback_p, cleanup_p )
lambda {
if writeback_p
lock(mboxfile) {|f|
mh.each_port do |port|
f.puts create_from_line(port)
port.ropen {|r|
f.puts r.read
}
end
}
end
if cleanup_p
Dir.foreach(mh.dirname) do |fname|
next if /\A\.\.?\z/ === fname
File.unlink "#{mh.dirname}/#{fname}"
end
Dir.rmdir mh.dirname
end
}
end
# make _From line
def UNIXMbox.create_from_line( port )
sprintf 'From %s %s',
fromaddr(), TextUtils.time2str(File.mtime(port.filename))
end
def UNIXMbox.fromaddr(port)
h = HeaderField.new_from_port(port, 'Return-Path') ||
HeaderField.new_from_port(port, 'From') ||
HeaderField.new_from_port(port, 'EnvelopeSender') or return 'nobody'
a = h.addrs[0] or return 'nobody'
a.spec
end
def close
return if @closed
ObjectSpace.undefine_finalizer self
@finalizer.call
@finalizer = nil
@real = nil
@closed = true
@updated = nil
end
def each_port( &block )
close_check
update
@real.each_port(&block)
end
alias each each_port
def reverse_each_port( &block )
close_check
update
@real.reverse_each_port(&block)
end
alias reverse_each reverse_each_port
# old #each_mail returns Port
#def each_mail( &block )
# each_port do |port|
# yield Mail.new(port)
# end
#end
def each_new_port( mtime = nil )
close_check
update
@real.each_new_port(mtime) {|p| yield p }
end
def new_port
close_check
@real.new_port
end
private
def close_check
@closed and raise ArgumentError, 'accessing already closed mbox'
end
def update
return if FileTest.zero?(@filename)
return if @updated and File.mtime(@filename) < @updated
w = nil
port = nil
time = nil
UNIXMbox.lock(@filename) {|f|
begin
f.each do |line|
if /\AFrom / === line
w.close if w
File.utime time, time, port.filename if time
port = @real.new_port
w = port.wopen
time = fromline2time(line)
else
w.print line if w
end
end
ensure
if w and not w.closed?
w.close
File.utime time, time, port.filename if time
end
end
f.truncate(0) unless @readonly
@updated = Time.now
}
end
def fromline2time( line )
m = /\AFrom \S+ \w+ (\w+) (\d+) (\d+):(\d+):(\d+) (\d+)/.match(line) \
or return nil
Time.local(m[6].to_i, m[1], m[2].to_i, m[3].to_i, m[4].to_i, m[5].to_i)
end
end # UNIXMbox
MboxLoader = UNIXMbox
class Maildir
extend Mutex_m
PORT_CLASS = MaildirPort
@seq = 0
def Maildir.unique_number
synchronize {
@seq += 1
return @seq
}
end
def initialize( dir = nil )
@dirname = dir || ENV['MAILDIR']
raise ArgumentError, "not directory: #{@dirname}"\
unless FileTest.directory? @dirname
@new = "#{@dirname}/new"
@tmp = "#{@dirname}/tmp"
@cur = "#{@dirname}/cur"
end
def directory
@dirname
end
def inspect
"#<#{self.class} #{@dirname}>"
end
def close
end
def each_port
mail_files(@cur).each do |path|
yield PORT_CLASS.new(path)
end
end
alias each each_port
def reverse_each_port
mail_files(@cur).reverse_each do |path|
yield PORT_CLASS.new(path)
end
end
alias reverse_each reverse_each_port
def new_port
fname = nil
tmpfname = nil
newfname = nil
begin
fname = "#{Time.now.to_i}.#{$$}_#{Maildir.unique_number}.#{Socket.gethostname}"
tmpfname = "#{@tmp}/#{fname}"
newfname = "#{@new}/#{fname}"
end while FileTest.exist? tmpfname
if block_given?
File.open(tmpfname, 'w') {|f| yield f }
File.rename tmpfname, newfname
PORT_CLASS.new(newfname)
else
File.open(tmpfname, 'w') {|f| f.write "\n\n" }
PORT_CLASS.new(tmpfname)
end
end
def each_new_port
mail_files(@new).each do |path|
dest = @cur + '/' + File.basename(path)
File.rename path, dest
yield PORT_CLASS.new(dest)
end
check_tmp
end
TOO_OLD = 60 * 60 * 36 # 36 hour
def check_tmp
old = Time.now.to_i - TOO_OLD
each_filename(@tmp) do |full, fname|
if FileTest.file? full and
File.stat(full).mtime.to_i < old
File.unlink full
end
end
end
private
def mail_files( dir )
Dir.entries(dir)\
.select {|s| s[0] != ?. }\
.sort_by {|s| s.slice(/\A\d+/).to_i }\
.map {|s| "#{dir}/#{s}" }\
.select {|path| FileTest.file? path }
end
def each_filename( dir )
Dir.foreach(dir) do |fname|
path = "#{dir}/#{fname}"
if fname[0] != ?. and FileTest.file? path
yield path, fname
end
end
end
end # Maildir
MaildirLoader = Maildir
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb | =begin rdoc
= Obsolete methods that are depriciated
If you really want to see them, go to lib/tmail/obsolete.rb and view to your
heart's content.
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
module TMail #:nodoc:
class Mail
alias include? key?
alias has_key? key?
def values
ret = []
each_field {|v| ret.push v }
ret
end
def value?( val )
HeaderField === val or return false
[ @header[val.name.downcase] ].flatten.include? val
end
alias has_value? value?
end
class Mail
def from_addr( default = nil )
addr, = from_addrs(nil)
addr || default
end
def from_address( default = nil )
if a = from_addr(nil)
a.spec
else
default
end
end
alias from_address= from_addrs=
def from_phrase( default = nil )
if a = from_addr(nil)
a.phrase
else
default
end
end
alias msgid message_id
alias msgid= message_id=
alias each_dest each_destination
end
class Address
alias route routes
alias addr spec
def spec=( str )
@local, @domain = str.split(/@/,2).map {|s| s.split(/\./) }
end
alias addr= spec=
alias address= spec=
end
class MhMailbox
alias new_mail new_port
alias each_mail each_port
alias each_newmail each_new_port
end
class UNIXMbox
alias new_mail new_port
alias each_mail each_port
alias each_newmail each_new_port
end
class Maildir
alias new_mail new_port
alias each_mail each_port
alias each_newmail each_new_port
end
extend TextUtils
class << self
alias msgid? message_id?
alias boundary new_boundary
alias msgid new_message_id
alias new_msgid new_message_id
end
def Mail.boundary
::TMail.new_boundary
end
def Mail.msgid
::TMail.new_message_id
end
end # module TMail
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb | #--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
module TMail
class Config
def initialize( strict )
@strict_parse = strict
@strict_base64decode = strict
end
def strict_parse?
@strict_parse
end
attr_writer :strict_parse
def strict_base64decode?
@strict_base64decode
end
attr_writer :strict_base64decode
def new_body_port( mail )
StringPort.new
end
alias new_preamble_port new_body_port
alias new_part_port new_body_port
end
DEFAULT_CONFIG = Config.new(false)
DEFAULT_STRICT_CONFIG = Config.new(true)
def Config.to_config( arg )
return DEFAULT_STRICT_CONFIG if arg == true
return DEFAULT_CONFIG if arg == false
arg or DEFAULT_CONFIG
end
end
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb | =begin rdoc
= Mail class
=end
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
require 'tmail/interface'
require 'tmail/encode'
require 'tmail/header'
require 'tmail/port'
require 'tmail/config'
require 'tmail/utils'
require 'tmail/attachments'
require 'tmail/quoting'
require 'socket'
module TMail
# == Mail Class
#
# Accessing a TMail object done via the TMail::Mail class. As email can be fairly complex
# creatures, you will find a large amount of accessor and setter methods in this class!
#
# Most of the below methods handle the header, in fact, what TMail does best is handle the
# header of the email object. There are only a few methods that deal directly with the body
# of the email, such as base64_encode and base64_decode.
#
# === Using TMail inside your code
#
# The usual way is to install the gem (see the {README}[link:/README] on how to do this) and
# then put at the top of your class:
#
# require 'tmail'
#
# You can then create a new TMail object in your code with:
#
# @email = TMail::Mail.new
#
# Or if you have an email as a string, you can initialize a new TMail::Mail object and get it
# to parse that string for you like so:
#
# @email = TMail::Mail.parse(email_text)
#
# You can also read a single email off the disk, for example:
#
# @email = TMail::Mail.load('filename.txt')
#
# Also, you can read a mailbox (usual unix mbox format) and end up with an array of TMail
# objects by doing something like this:
#
# # Note, we pass true as the last variable to open the mailbox read only
# mailbox = TMail::UNIXMbox.new("mailbox", nil, true)
# @emails = []
# mailbox.each_port { |m| @emails << TMail::Mail.new(m) }
#
class Mail
class << self
# Opens an email that has been saved out as a file by itself.
#
# This function will read a file non-destructively and then parse
# the contents and return a TMail::Mail object.
#
# Does not handle multiple email mailboxes (like a unix mbox) for that
# use the TMail::UNIXMbox class.
#
# Example:
# mail = TMail::Mail.load('filename')
#
def load( fname )
new(FilePort.new(fname))
end
alias load_from load
alias loadfrom load
# Parses an email from the supplied string and returns a TMail::Mail
# object.
#
# Example:
# require 'rubygems'; require 'tmail'
# email_string =<<HEREDOC
# To: mikel@lindsaar.net
# From: mikel@me.com
# Subject: This is a short Email
#
# Hello there Mikel!
#
# HEREDOC
# mail = TMail::Mail.parse(email_string)
# #=> #<TMail::Mail port=#<TMail::StringPort:id=0xa30ac0> bodyport=nil>
# mail.body
# #=> "Hello there Mikel!\n\n"
def parse( str )
new(StringPort.new(str))
end
end
def initialize( port = nil, conf = DEFAULT_CONFIG ) #:nodoc:
@port = port || StringPort.new
@config = Config.to_config(conf)
@header = {}
@body_port = nil
@body_parsed = false
@epilogue = ''
@parts = []
@port.ropen {|f|
parse_header f
parse_body f unless @port.reproducible?
}
end
# Provides access to the port this email is using to hold it's data
#
# Example:
# mail = TMail::Mail.parse(email_string)
# mail.port
# #=> #<TMail::StringPort:id=0xa2c952>
attr_reader :port
def inspect
"\#<#{self.class} port=#{@port.inspect} bodyport=#{@body_port.inspect}>"
end
#
# to_s interfaces
#
public
include StrategyInterface
def write_back( eol = "\n", charset = 'e' )
parse_body
@port.wopen {|stream| encoded eol, charset, stream }
end
def accept( strategy )
with_multipart_encoding(strategy) {
ordered_each do |name, field|
next if field.empty?
strategy.header_name canonical(name)
field.accept strategy
strategy.puts
end
strategy.puts
body_port().ropen {|r|
strategy.write r.read
}
}
end
private
def canonical( name )
name.split(/-/).map {|s| s.capitalize }.join('-')
end
def with_multipart_encoding( strategy )
if parts().empty? # DO NOT USE @parts
yield
else
bound = ::TMail.new_boundary
if @header.key? 'content-type'
@header['content-type'].params['boundary'] = bound
else
store 'Content-Type', %<multipart/mixed; boundary="#{bound}">
end
yield
parts().each do |tm|
strategy.puts
strategy.puts '--' + bound
tm.accept strategy
end
strategy.puts
strategy.puts '--' + bound + '--'
strategy.write epilogue()
end
end
###
### header
###
public
ALLOW_MULTIPLE = {
'received' => true,
'resent-date' => true,
'resent-from' => true,
'resent-sender' => true,
'resent-to' => true,
'resent-cc' => true,
'resent-bcc' => true,
'resent-message-id' => true,
'comments' => true,
'keywords' => true
}
USE_ARRAY = ALLOW_MULTIPLE
def header
@header.dup
end
# Returns a TMail::AddressHeader object of the field you are querying.
# Examples:
# @mail['from'] #=> #<TMail::AddressHeader "mikel@test.com.au">
# @mail['to'] #=> #<TMail::AddressHeader "mikel@test.com.au">
#
# You can get the string value of this by passing "to_s" to the query:
# Example:
# @mail['to'].to_s #=> "mikel@test.com.au"
def []( key )
@header[key.downcase]
end
def sub_header(key, param)
(hdr = self[key]) ? hdr[param] : nil
end
alias fetch []
# Allows you to set or delete TMail header objects at will.
# Examples:
# @mail = TMail::Mail.new
# @mail['to'].to_s # => 'mikel@test.com.au'
# @mail['to'] = 'mikel@elsewhere.org'
# @mail['to'].to_s # => 'mikel@elsewhere.org'
# @mail.encoded # => "To: mikel@elsewhere.org\r\n\r\n"
# @mail['to'] = nil
# @mail['to'].to_s # => nil
# @mail.encoded # => "\r\n"
#
# Note: setting mail[] = nil actually deletes the header field in question from the object,
# it does not just set the value of the hash to nil
def []=( key, val )
dkey = key.downcase
if val.nil?
@header.delete dkey
return nil
end
case val
when String
header = new_hf(key, val)
when HeaderField
;
when Array
ALLOW_MULTIPLE.include? dkey or
raise ArgumentError, "#{key}: Header must not be multiple"
@header[dkey] = val
return val
else
header = new_hf(key, val.to_s)
end
if ALLOW_MULTIPLE.include? dkey
(@header[dkey] ||= []).push header
else
@header[dkey] = header
end
val
end
alias store []=
# Allows you to loop through each header in the TMail::Mail object in a block
# Example:
# @mail['to'] = 'mikel@elsewhere.org'
# @mail['from'] = 'me@me.com'
# @mail.each_header { |k,v| puts "#{k} = #{v}" }
# # => from = me@me.com
# # => to = mikel@elsewhere.org
def each_header
@header.each do |key, val|
[val].flatten.each {|v| yield key, v }
end
end
alias each_pair each_header
def each_header_name( &block )
@header.each_key(&block)
end
alias each_key each_header_name
def each_field( &block )
@header.values.flatten.each(&block)
end
alias each_value each_field
FIELD_ORDER = %w(
return-path received
resent-date resent-from resent-sender resent-to
resent-cc resent-bcc resent-message-id
date from sender reply-to to cc bcc
message-id in-reply-to references
subject comments keywords
mime-version content-type content-transfer-encoding
content-disposition content-description
)
def ordered_each
list = @header.keys
FIELD_ORDER.each do |name|
if list.delete(name)
[@header[name]].flatten.each {|v| yield name, v }
end
end
list.each do |name|
[@header[name]].flatten.each {|v| yield name, v }
end
end
def clear
@header.clear
end
def delete( key )
@header.delete key.downcase
end
def delete_if
@header.delete_if do |key,val|
if Array === val
val.delete_if {|v| yield key, v }
val.empty?
else
yield key, val
end
end
end
def keys
@header.keys
end
def key?( key )
@header.key? key.downcase
end
def values_at( *args )
args.map {|k| @header[k.downcase] }.flatten
end
alias indexes values_at
alias indices values_at
private
def parse_header( f )
name = field = nil
unixfrom = nil
while line = f.gets
case line
when /\A[ \t]/ # continue from prev line
raise SyntaxError, 'mail is began by space' unless field
field << ' ' << line.strip
when /\A([^\: \t]+):\s*/ # new header line
add_hf name, field if field
name = $1
field = $' #.strip
when /\A\-*\s*\z/ # end of header
add_hf name, field if field
name = field = nil
break
when /\AFrom (\S+)/
unixfrom = $1
when /^charset=.*/
else
raise SyntaxError, "wrong mail header: '#{line.inspect}'"
end
end
add_hf name, field if name
if unixfrom
add_hf 'Return-Path', "<#{unixfrom}>" unless @header['return-path']
end
end
def add_hf( name, field )
key = name.downcase
field = new_hf(name, field)
if ALLOW_MULTIPLE.include? key
(@header[key] ||= []).push field
else
@header[key] = field
end
end
def new_hf( name, field )
HeaderField.new(name, field, @config)
end
###
### body
###
public
def body_port
parse_body
@body_port
end
def each( &block )
body_port().ropen {|f| f.each(&block) }
end
def quoted_body
body_port.ropen {|f| return f.read }
end
def quoted_body= str
body_port.wopen { |f| f.write str }
str
end
def body=( str )
# Sets the body of the email to a new (encoded) string.
#
# We also reparses the email if the body is ever reassigned, this is a performance hit, however when
# you assign the body, you usually want to be able to make sure that you can access the attachments etc.
#
# Usage:
#
# mail.body = "Hello, this is\nthe body text"
# # => "Hello, this is\nthe body"
# mail.body
# # => "Hello, this is\nthe body"
@body_parsed = false
parse_body(StringInput.new(str))
parse_body
@body_port.wopen {|f| f.write str }
str
end
alias preamble quoted_body
alias preamble= quoted_body=
def epilogue
parse_body
@epilogue.dup
end
def epilogue=( str )
parse_body
@epilogue = str
str
end
def parts
parse_body
@parts
end
def each_part( &block )
parts().each(&block)
end
# Returns true if the content type of this part of the email is
# a disposition attachment
def disposition_is_attachment?
(self['content-disposition'] && self['content-disposition'].disposition == "attachment")
end
# Returns true if this part's content main type is text, else returns false.
# By main type is meant "text/plain" is text. "text/html" is text
def content_type_is_text?
self.header['content-type'] && (self.header['content-type'].main_type != "text")
end
private
def parse_body( f = nil )
return if @body_parsed
if f
parse_body_0 f
else
@port.ropen {|f|
skip_header f
parse_body_0 f
}
end
@body_parsed = true
end
def skip_header( f )
while line = f.gets
return if /\A[\r\n]*\z/ === line
end
end
def parse_body_0( f )
if multipart?
read_multipart f
else
@body_port = @config.new_body_port(self)
@body_port.wopen {|w|
w.write f.read
}
end
end
def read_multipart( src )
bound = @header['content-type'].params['boundary']
is_sep = /\A--#{Regexp.quote bound}(?:--)?[ \t]*(?:\n|\r\n|\r)/
lastbound = "--#{bound}--"
ports = [ @config.new_preamble_port(self) ]
begin
f = ports.last.wopen
while line = src.gets
if is_sep === line
f.close
break if line.strip == lastbound
ports.push @config.new_part_port(self)
f = ports.last.wopen
else
f << line
end
end
@epilogue = (src.read || '')
ensure
f.close if f and not f.closed?
end
@body_port = ports.shift
@parts = ports.map {|p| self.class.new(p, @config) }
end
end # class Mail
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb | =begin rdoc
= Quoting methods
=end
module TMail
class Mail
def subject(to_charset = 'utf-8')
Unquoter.unquote_and_convert_to(quoted_subject, to_charset)
end
def unquoted_body(to_charset = 'utf-8')
from_charset = sub_header("content-type", "charset")
case (content_transfer_encoding || "7bit").downcase
when "quoted-printable"
# the default charset is set to iso-8859-1 instead of 'us-ascii'.
# This is needed as many mailer do not set the charset but send in ISO. This is only used if no charset is set.
if !from_charset.blank? && from_charset.downcase == 'us-ascii'
from_charset = 'iso-8859-1'
end
Unquoter.unquote_quoted_printable_and_convert_to(quoted_body,
to_charset, from_charset, true)
when "base64"
Unquoter.unquote_base64_and_convert_to(quoted_body, to_charset,
from_charset)
when "7bit", "8bit"
Unquoter.convert_to(quoted_body, to_charset, from_charset)
when "binary"
quoted_body
else
quoted_body
end
end
def body(to_charset = 'utf-8', &block)
attachment_presenter = block || Proc.new { |file_name| "Attachment: #{file_name}\n" }
if multipart?
parts.collect { |part|
header = part["content-type"]
if part.multipart?
part.body(to_charset, &attachment_presenter)
elsif header.nil?
""
elsif !attachment?(part)
part.unquoted_body(to_charset)
else
attachment_presenter.call(header["name"] || "(unnamed)")
end
}.join
else
unquoted_body(to_charset)
end
end
end
class Unquoter
class << self
def unquote_and_convert_to(text, to_charset, from_charset = "iso-8859-1", preserve_underscores=false)
return "" if text.nil?
text.gsub(/(.*?)(?:(?:=\?(.*?)\?(.)\?(.*?)\?=)|$)/) do
before = $1
from_charset = $2
quoting_method = $3
text = $4
before = convert_to(before, to_charset, from_charset) if before.length > 0
before + case quoting_method
when "q", "Q" then
unquote_quoted_printable_and_convert_to(text, to_charset, from_charset, preserve_underscores)
when "b", "B" then
unquote_base64_and_convert_to(text, to_charset, from_charset)
when nil then
# will be nil at the end of the string, due to the nature of
# the regex used.
""
else
raise "unknown quoting method #{quoting_method.inspect}"
end
end
end
def unquote_quoted_printable_and_convert_to(text, to, from, preserve_underscores=false)
text = text.gsub(/_/, " ") unless preserve_underscores
text = text.gsub(/\r\n|\r/, "\n") # normalize newlines
convert_to(text.unpack("M*").first, to, from)
end
def unquote_base64_and_convert_to(text, to, from)
convert_to(Base64.decode(text), to, from)
end
begin
require 'iconv'
def convert_to(text, to, from)
return text unless to && from
text ? Iconv.iconv(to, from, text).first : ""
rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
# the 'from' parameter specifies a charset other than what the text
# actually is...not much we can do in this case but just return the
# unconverted text.
#
# Ditto if either parameter represents an unknown charset, like
# X-UNKNOWN.
text
end
rescue LoadError
# Not providing quoting support
def convert_to(text, to, from)
warn "Action Mailer: iconv not loaded; ignoring conversion from #{from} to #{to} (#{__FILE__}:#{__LINE__})"
text
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb | #--
# = COPYRIGHT:
#
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
require 'nkf'
require 'tmail/base64'
require 'tmail/stringio'
require 'tmail/utils'
#:startdoc:
module TMail
#:stopdoc:
class << self
attr_accessor :KCODE
end
self.KCODE = 'NONE'
module StrategyInterface
def create_dest( obj )
case obj
when nil
StringOutput.new
when String
StringOutput.new(obj)
when IO, StringOutput
obj
else
raise TypeError, 'cannot handle this type of object for dest'
end
end
module_function :create_dest
#:startdoc:
# Returns the TMail object encoded and ready to be sent via SMTP etc.
# You should call this before you are packaging up your email to
# correctly escape all the values that need escaping in the email, line
# wrap the email etc.
#
# It is also a good idea to call this before you marshal or serialize
# a TMail object.
#
# For Example:
#
# email = TMail::Load(my_email_file)
# email_to_send = email.encoded
def encoded( eol = "\r\n", charset = 'j', dest = nil )
accept_strategy Encoder, eol, charset, dest
end
# Returns the TMail object decoded and ready to be used by you, your
# program etc.
#
# You should call this before you are packaging up your email to
# correctly escape all the values that need escaping in the email, line
# wrap the email etc.
#
# For Example:
#
# email = TMail::Load(my_email_file)
# email_to_send = email.encoded
def decoded( eol = "\n", charset = 'e', dest = nil )
# Turn the E-Mail into a string and return it with all
# encoded characters decoded. alias for to_s
accept_strategy Decoder, eol, charset, dest
end
alias to_s decoded
def accept_strategy( klass, eol, charset, dest = nil ) #:nodoc:
dest ||= ''
accept klass.new( create_dest(dest), charset, eol )
dest
end
end
#:stopdoc:
###
### MIME B encoding decoder
###
class Decoder
include TextUtils
encoded = '=\?(?:iso-2022-jp|euc-jp|shift_jis)\?[QB]\?[a-z0-9+/=]+\?='
ENCODED_WORDS = /#{encoded}(?:\s+#{encoded})*/i
OUTPUT_ENCODING = {
'EUC' => 'e',
'SJIS' => 's',
}
def self.decode( str, encoding = nil )
encoding ||= (OUTPUT_ENCODING[TMail.KCODE] || 'j')
opt = '-mS' + encoding
str.gsub(ENCODED_WORDS) {|s| NKF.nkf(opt, s) }
end
def initialize( dest, encoding = nil, eol = "\n" )
@f = StrategyInterface.create_dest(dest)
@encoding = (/\A[ejs]/ === encoding) ? encoding[0,1] : nil
@eol = eol
end
def decode( str )
self.class.decode(str, @encoding)
end
private :decode
def terminate
end
def header_line( str )
@f << decode(str)
end
def header_name( nm )
@f << nm << ': '
end
def header_body( str )
@f << decode(str)
end
def space
@f << ' '
end
alias spc space
def lwsp( str )
@f << str
end
def meta( str )
@f << str
end
def text( str )
@f << decode(str)
end
def phrase( str )
@f << quote_phrase(decode(str))
end
def kv_pair( k, v )
v = dquote(v) unless token_safe?(v)
@f << k << '=' << v
end
def puts( str = nil )
@f << str if str
@f << @eol
end
def write( str )
@f << str
end
end
###
### MIME B-encoding encoder
###
#
# FIXME: This class can handle only (euc-jp/shift_jis -> iso-2022-jp).
#
class Encoder
include TextUtils
BENCODE_DEBUG = false unless defined?(BENCODE_DEBUG)
def Encoder.encode( str )
e = new()
e.header_body str
e.terminate
e.dest.string
end
SPACER = "\t"
MAX_LINE_LEN = 78
RFC_2822_MAX_LENGTH = 998
OPTIONS = {
'EUC' => '-Ej -m0',
'SJIS' => '-Sj -m0',
'UTF8' => nil, # FIXME
'NONE' => nil
}
def initialize( dest = nil, encoding = nil, eol = "\r\n", limit = nil )
@f = StrategyInterface.create_dest(dest)
@opt = OPTIONS[TMail.KCODE]
@eol = eol
@folded = false
@preserve_quotes = true
reset
end
def preserve_quotes=( bool )
@preserve_quotes
end
def preserve_quotes
@preserve_quotes
end
def normalize_encoding( str )
if @opt
then NKF.nkf(@opt, str)
else str
end
end
def reset
@text = ''
@lwsp = ''
@curlen = 0
end
def terminate
add_lwsp ''
reset
end
def dest
@f
end
def puts( str = nil )
@f << str if str
@f << @eol
end
def write( str )
@f << str
end
#
# add
#
def header_line( line )
scanadd line
end
def header_name( name )
add_text name.split(/-/).map {|i| i.capitalize }.join('-')
add_text ':'
add_lwsp ' '
end
def header_body( str )
scanadd normalize_encoding(str)
end
def space
add_lwsp ' '
end
alias spc space
def lwsp( str )
add_lwsp str.sub(/[\r\n]+[^\r\n]*\z/, '')
end
def meta( str )
add_text str
end
def text( str )
scanadd normalize_encoding(str)
end
def phrase( str )
str = normalize_encoding(str)
if CONTROL_CHAR === str
scanadd str
else
add_text quote_phrase(str)
end
end
# FIXME: implement line folding
#
def kv_pair( k, v )
return if v.nil?
v = normalize_encoding(v)
if token_safe?(v)
add_text k + '=' + v
elsif not CONTROL_CHAR === v
add_text k + '=' + quote_token(v)
else
# apply RFC2231 encoding
kv = k + '*=' + "iso-2022-jp'ja'" + encode_value(v)
add_text kv
end
end
def encode_value( str )
str.gsub(TOKEN_UNSAFE) {|s| '%%%02x' % s[0] }
end
private
def scanadd( str, force = false )
types = ''
strs = []
if str.respond_to?(:encoding)
enc = str.encoding
str.force_encoding(Encoding::ASCII_8BIT)
end
until str.empty?
if m = /\A[^\e\t\r\n ]+/.match(str)
types << (force ? 'j' : 'a')
if str.respond_to?(:encoding)
strs.push m[0].force_encoding(enc)
else
strs.push m[0]
end
elsif m = /\A[\t\r\n ]+/.match(str)
types << 's'
if str.respond_to?(:encoding)
strs.push m[0].force_encoding(enc)
else
strs.push m[0]
end
elsif m = /\A\e../.match(str)
esc = m[0]
str = m.post_match
if esc != "\e(B" and m = /\A[^\e]+/.match(str)
types << 'j'
if str.respond_to?(:encoding)
strs.push m[0].force_encoding(enc)
else
strs.push m[0]
end
end
else
raise 'TMail FATAL: encoder scan fail'
end
(str = m.post_match) unless m.nil?
end
do_encode types, strs
end
def do_encode( types, strs )
#
# result : (A|E)(S(A|E))*
# E : W(SW)*
# W : (J|A)+ but must contain J # (J|A)*J(J|A)*
# A : <<A character string not to be encoded>>
# J : <<A character string to be encoded>>
# S : <<LWSP>>
#
# An encoding unit is `E'.
# Input (parameter `types') is (J|A)(J|A|S)*(J|A)
#
if BENCODE_DEBUG
puts
puts '-- do_encode ------------'
puts types.split(//).join(' ')
p strs
end
e = /[ja]*j[ja]*(?:s[ja]*j[ja]*)*/
while m = e.match(types)
pre = m.pre_match
concat_A_S pre, strs[0, pre.size] unless pre.empty?
concat_E m[0], strs[m.begin(0) ... m.end(0)]
types = m.post_match
strs.slice! 0, m.end(0)
end
concat_A_S types, strs
end
def concat_A_S( types, strs )
if RUBY_VERSION < '1.9'
a = ?a; s = ?s
else
a = 'a'.ord; s = 's'.ord
end
i = 0
types.each_byte do |t|
case t
when a then add_text strs[i]
when s then add_lwsp strs[i]
else
raise "TMail FATAL: unknown flag: #{t.chr}"
end
i += 1
end
end
METHOD_ID = {
?j => :extract_J,
?e => :extract_E,
?a => :extract_A,
?s => :extract_S
}
def concat_E( types, strs )
if BENCODE_DEBUG
puts '---- concat_E'
puts "types=#{types.split(//).join(' ')}"
puts "strs =#{strs.inspect}"
end
flush() unless @text.empty?
chunk = ''
strs.each_with_index do |s,i|
mid = METHOD_ID[types[i]]
until s.empty?
unless c = __send__(mid, chunk.size, s)
add_with_encode chunk unless chunk.empty?
flush
chunk = ''
fold
c = __send__(mid, 0, s)
raise 'TMail FATAL: extract fail' unless c
end
chunk << c
end
end
add_with_encode chunk unless chunk.empty?
end
def extract_J( chunksize, str )
size = max_bytes(chunksize, str.size) - 6
size = (size % 2 == 0) ? (size) : (size - 1)
return nil if size <= 0
if str.respond_to?(:encoding)
enc = str.encoding
str.force_encoding(Encoding::ASCII_8BIT)
"\e$B#{str.slice!(0, size)}\e(B".force_encoding(enc)
else
"\e$B#{str.slice!(0, size)}\e(B"
end
end
def extract_A( chunksize, str )
size = max_bytes(chunksize, str.size)
return nil if size <= 0
str.slice!(0, size)
end
alias extract_S extract_A
def max_bytes( chunksize, ssize )
(restsize() - '=?iso-2022-jp?B??='.size) / 4 * 3 - chunksize
end
#
# free length buffer
#
def add_text( str )
@text << str
# puts '---- text -------------------------------------'
# puts "+ #{str.inspect}"
# puts "txt >>>#{@text.inspect}<<<"
end
def add_with_encode( str )
@text << "=?iso-2022-jp?B?#{Base64.encode(str)}?="
end
def add_lwsp( lwsp )
# puts '---- lwsp -------------------------------------'
# puts "+ #{lwsp.inspect}"
fold if restsize() <= 0
flush(@folded)
@lwsp = lwsp
end
def flush(folded = false)
# puts '---- flush ----'
# puts "spc >>>#{@lwsp.inspect}<<<"
# puts "txt >>>#{@text.inspect}<<<"
@f << @lwsp << @text
if folded
@curlen = 0
else
@curlen += (@lwsp.size + @text.size)
end
@text = ''
@lwsp = ''
end
def fold
# puts '---- fold ----'
unless @f.string =~ /^.*?:$/
@f << @eol
@lwsp = SPACER
else
fold_header
@folded = true
end
@curlen = 0
end
def fold_header
# Called because line is too long - so we need to wrap.
# First look for whitespace in the text
# if it has text, fold there
# check the remaining text, if too long, fold again
# if it doesn't, then don't fold unless the line goes beyond 998 chars
# Check the text to see if there is whitespace, or if not
@wrapped_text = []
until @text.blank?
fold_the_string
end
@text = @wrapped_text.join("#{@eol}#{SPACER}")
end
def fold_the_string
whitespace_location = @text =~ /\s/ || @text.length
# Is the location of the whitespace shorter than the RCF_2822_MAX_LENGTH?
# if there is no whitespace in the string, then this
unless mazsize(whitespace_location) <= 0
@text.strip!
@wrapped_text << @text.slice!(0...whitespace_location)
# If it is not less, we have to wrap it destructively
else
slice_point = RFC_2822_MAX_LENGTH - @curlen - @lwsp.length
@text.strip!
@wrapped_text << @text.slice!(0...slice_point)
end
end
def restsize
MAX_LINE_LEN - (@curlen + @lwsp.size + @text.size)
end
def mazsize(whitespace_location)
# Per RFC2822, the maximum length of a line is 998 chars
RFC_2822_MAX_LENGTH - (@curlen + @lwsp.size + whitespace_location)
end
end
#:startdoc:
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb | #--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
require 'tmail/encode'
require 'tmail/address'
require 'tmail/parser'
require 'tmail/config'
require 'tmail/utils'
#:startdoc:
module TMail
# Provides methods to handle and manipulate headers in the email
class HeaderField
include TextUtils
class << self
alias newobj new
def new( name, body, conf = DEFAULT_CONFIG )
klass = FNAME_TO_CLASS[name.downcase] || UnstructuredHeader
klass.newobj body, conf
end
# Returns a HeaderField object matching the header you specify in the "name" param.
# Requires an initialized TMail::Port to be passed in.
#
# The method searches the header of the Port you pass into it to find a match on
# the header line you pass. Once a match is found, it will unwrap the matching line
# as needed to return an initialized HeaderField object.
#
# If you want to get the Envelope sender of the email object, pass in "EnvelopeSender",
# if you want the From address of the email itself, pass in 'From'.
#
# This is because a mailbox doesn't have the : after the From that designates the
# beginning of the envelope sender (which can be different to the from address of
# the email)
#
# Other fields can be passed as normal, "Reply-To", "Received" etc.
#
# Note: Change of behaviour in 1.2.1 => returns nil if it does not find the specified
# header field, otherwise returns an instantiated object of the correct header class
#
# For example:
# port = TMail::FilePort.new("/test/fixtures/raw_email_simple")
# h = TMail::HeaderField.new_from_port(port, "From")
# h.addrs.to_s #=> "Mikel Lindsaar <mikel@nowhere.com>"
# h = TMail::HeaderField.new_from_port(port, "EvelopeSender")
# h.addrs.to_s #=> "mike@anotherplace.com.au"
# h = TMail::HeaderField.new_from_port(port, "SomeWeirdHeaderField")
# h #=> nil
def new_from_port( port, name, conf = DEFAULT_CONFIG )
if name == "EnvelopeSender"
name = "From"
re = Regexp.new('\A(From) ', 'i')
else
re = Regexp.new('\A(' + Regexp.quote(name) + '):', 'i')
end
str = nil
port.ropen {|f|
f.each do |line|
if m = re.match(line) then str = m.post_match.strip
elsif str and /\A[\t ]/ === line then str << ' ' << line.strip
elsif /\A-*\s*\z/ === line then break
elsif str then break
end
end
}
new(name, str, Config.to_config(conf)) if str
end
def internal_new( name, conf )
FNAME_TO_CLASS[name].newobj('', conf, true)
end
end # class << self
def initialize( body, conf, intern = false )
@body = body
@config = conf
@illegal = false
@parsed = false
if intern
@parsed = true
parse_init
end
end
def inspect
"#<#{self.class} #{@body.inspect}>"
end
def illegal?
@illegal
end
def empty?
ensure_parsed
return true if @illegal
isempty?
end
private
def ensure_parsed
return if @parsed
@parsed = true
parse
end
# defabstract parse
# end
def clear_parse_status
@parsed = false
@illegal = false
end
public
def body
ensure_parsed
v = Decoder.new(s = '')
do_accept v
v.terminate
s
end
def body=( str )
@body = str
clear_parse_status
end
include StrategyInterface
def accept( strategy )
ensure_parsed
do_accept strategy
strategy.terminate
end
# abstract do_accept
end
class UnstructuredHeader < HeaderField
def body
ensure_parsed
@body
end
def body=( arg )
ensure_parsed
@body = arg
end
private
def parse_init
end
def parse
@body = Decoder.decode(@body.gsub(/\n|\r\n|\r/, ''))
end
def isempty?
not @body
end
def do_accept( strategy )
strategy.text @body
end
end
class StructuredHeader < HeaderField
def comments
ensure_parsed
if @comments[0]
[Decoder.decode(@comments[0])]
else
@comments
end
end
private
def parse
save = nil
begin
parse_init
do_parse
rescue SyntaxError
if not save and mime_encoded? @body
save = @body
@body = Decoder.decode(save)
retry
elsif save
@body = save
end
@illegal = true
raise if @config.strict_parse?
end
end
def parse_init
@comments = []
init
end
def do_parse
quote_boundary
obj = Parser.parse(self.class::PARSE_TYPE, @body, @comments)
set obj if obj
end
end
class DateTimeHeader < StructuredHeader
PARSE_TYPE = :DATETIME
def date
ensure_parsed
@date
end
def date=( arg )
ensure_parsed
@date = arg
end
private
def init
@date = nil
end
def set( t )
@date = t
end
def isempty?
not @date
end
def do_accept( strategy )
strategy.meta time2str(@date)
end
end
class AddressHeader < StructuredHeader
PARSE_TYPE = :MADDRESS
def addrs
ensure_parsed
@addrs
end
private
def init
@addrs = []
end
def set( a )
@addrs = a
end
def isempty?
@addrs.empty?
end
def do_accept( strategy )
first = true
@addrs.each do |a|
if first
first = false
else
strategy.meta ','
strategy.space
end
a.accept strategy
end
@comments.each do |c|
strategy.space
strategy.meta '('
strategy.text c
strategy.meta ')'
end
end
end
class ReturnPathHeader < AddressHeader
PARSE_TYPE = :RETPATH
def addr
addrs()[0]
end
def spec
a = addr() or return nil
a.spec
end
def routes
a = addr() or return nil
a.routes
end
private
def do_accept( strategy )
a = addr()
strategy.meta '<'
unless a.routes.empty?
strategy.meta a.routes.map {|i| '@' + i }.join(',')
strategy.meta ':'
end
spec = a.spec
strategy.meta spec if spec
strategy.meta '>'
end
end
class SingleAddressHeader < AddressHeader
def addr
addrs()[0]
end
private
def do_accept( strategy )
a = addr()
a.accept strategy
@comments.each do |c|
strategy.space
strategy.meta '('
strategy.text c
strategy.meta ')'
end
end
end
class MessageIdHeader < StructuredHeader
def id
ensure_parsed
@id
end
def id=( arg )
ensure_parsed
@id = arg
end
private
def init
@id = nil
end
def isempty?
not @id
end
def do_parse
@id = @body.slice(MESSAGE_ID) or
raise SyntaxError, "wrong Message-ID format: #{@body}"
end
def do_accept( strategy )
strategy.meta @id
end
end
class ReferencesHeader < StructuredHeader
def refs
ensure_parsed
@refs
end
def each_id
self.refs.each do |i|
yield i if MESSAGE_ID === i
end
end
def ids
ensure_parsed
@ids
end
def each_phrase
self.refs.each do |i|
yield i unless MESSAGE_ID === i
end
end
def phrases
ret = []
each_phrase {|i| ret.push i }
ret
end
private
def init
@refs = []
@ids = []
end
def isempty?
@ids.empty?
end
def do_parse
str = @body
while m = MESSAGE_ID.match(str)
pre = m.pre_match.strip
@refs.push pre unless pre.empty?
@refs.push s = m[0]
@ids.push s
str = m.post_match
end
str = str.strip
@refs.push str unless str.empty?
end
def do_accept( strategy )
first = true
@ids.each do |i|
if first
first = false
else
strategy.space
end
strategy.meta i
end
end
end
class ReceivedHeader < StructuredHeader
PARSE_TYPE = :RECEIVED
def from
ensure_parsed
@from
end
def from=( arg )
ensure_parsed
@from = arg
end
def by
ensure_parsed
@by
end
def by=( arg )
ensure_parsed
@by = arg
end
def via
ensure_parsed
@via
end
def via=( arg )
ensure_parsed
@via = arg
end
def with
ensure_parsed
@with
end
def id
ensure_parsed
@id
end
def id=( arg )
ensure_parsed
@id = arg
end
def _for
ensure_parsed
@_for
end
def _for=( arg )
ensure_parsed
@_for = arg
end
def date
ensure_parsed
@date
end
def date=( arg )
ensure_parsed
@date = arg
end
private
def init
@from = @by = @via = @with = @id = @_for = nil
@with = []
@date = nil
end
def set( args )
@from, @by, @via, @with, @id, @_for, @date = *args
end
def isempty?
@with.empty? and not (@from or @by or @via or @id or @_for or @date)
end
def do_accept( strategy )
list = []
list.push 'from ' + @from if @from
list.push 'by ' + @by if @by
list.push 'via ' + @via if @via
@with.each do |i|
list.push 'with ' + i
end
list.push 'id ' + @id if @id
list.push 'for <' + @_for + '>' if @_for
first = true
list.each do |i|
strategy.space unless first
strategy.meta i
first = false
end
if @date
strategy.meta ';'
strategy.space
strategy.meta time2str(@date)
end
end
end
class KeywordsHeader < StructuredHeader
PARSE_TYPE = :KEYWORDS
def keys
ensure_parsed
@keys
end
private
def init
@keys = []
end
def set( a )
@keys = a
end
def isempty?
@keys.empty?
end
def do_accept( strategy )
first = true
@keys.each do |i|
if first
first = false
else
strategy.meta ','
end
strategy.meta i
end
end
end
class EncryptedHeader < StructuredHeader
PARSE_TYPE = :ENCRYPTED
def encrypter
ensure_parsed
@encrypter
end
def encrypter=( arg )
ensure_parsed
@encrypter = arg
end
def keyword
ensure_parsed
@keyword
end
def keyword=( arg )
ensure_parsed
@keyword = arg
end
private
def init
@encrypter = nil
@keyword = nil
end
def set( args )
@encrypter, @keyword = args
end
def isempty?
not (@encrypter or @keyword)
end
def do_accept( strategy )
if @key
strategy.meta @encrypter + ','
strategy.space
strategy.meta @keyword
else
strategy.meta @encrypter
end
end
end
class MimeVersionHeader < StructuredHeader
PARSE_TYPE = :MIMEVERSION
def major
ensure_parsed
@major
end
def major=( arg )
ensure_parsed
@major = arg
end
def minor
ensure_parsed
@minor
end
def minor=( arg )
ensure_parsed
@minor = arg
end
def version
sprintf('%d.%d', major, minor)
end
private
def init
@major = nil
@minor = nil
end
def set( args )
@major, @minor = *args
end
def isempty?
not (@major or @minor)
end
def do_accept( strategy )
strategy.meta sprintf('%d.%d', @major, @minor)
end
end
class ContentTypeHeader < StructuredHeader
PARSE_TYPE = :CTYPE
def main_type
ensure_parsed
@main
end
def main_type=( arg )
ensure_parsed
@main = arg.downcase
end
def sub_type
ensure_parsed
@sub
end
def sub_type=( arg )
ensure_parsed
@sub = arg.downcase
end
def content_type
ensure_parsed
@sub ? sprintf('%s/%s', @main, @sub) : @main
end
def params
ensure_parsed
unless @params.blank?
@params.each do |k, v|
@params[k] = unquote(v)
end
end
@params
end
def []( key )
ensure_parsed
@params and unquote(@params[key])
end
def []=( key, val )
ensure_parsed
(@params ||= {})[key] = val
end
private
def init
@main = @sub = @params = nil
end
def set( args )
@main, @sub, @params = *args
end
def isempty?
not (@main or @sub)
end
def do_accept( strategy )
if @sub
strategy.meta sprintf('%s/%s', @main, @sub)
else
strategy.meta @main
end
@params.each do |k,v|
if v
strategy.meta ';'
strategy.space
strategy.kv_pair k, v
end
end
end
end
class ContentTransferEncodingHeader < StructuredHeader
PARSE_TYPE = :CENCODING
def encoding
ensure_parsed
@encoding
end
def encoding=( arg )
ensure_parsed
@encoding = arg
end
private
def init
@encoding = nil
end
def set( s )
@encoding = s
end
def isempty?
not @encoding
end
def do_accept( strategy )
strategy.meta @encoding.capitalize
end
end
class ContentDispositionHeader < StructuredHeader
PARSE_TYPE = :CDISPOSITION
def disposition
ensure_parsed
@disposition
end
def disposition=( str )
ensure_parsed
@disposition = str.downcase
end
def params
ensure_parsed
unless @params.blank?
@params.each do |k, v|
@params[k] = unquote(v)
end
end
@params
end
def []( key )
ensure_parsed
@params and unquote(@params[key])
end
def []=( key, val )
ensure_parsed
(@params ||= {})[key] = val
end
private
def init
@disposition = @params = nil
end
def set( args )
@disposition, @params = *args
end
def isempty?
not @disposition and (not @params or @params.empty?)
end
def do_accept( strategy )
strategy.meta @disposition
@params.each do |k,v|
strategy.meta ';'
strategy.space
strategy.kv_pair k, unquote(v)
end
end
end
class HeaderField # redefine
FNAME_TO_CLASS = {
'date' => DateTimeHeader,
'resent-date' => DateTimeHeader,
'to' => AddressHeader,
'cc' => AddressHeader,
'bcc' => AddressHeader,
'from' => AddressHeader,
'reply-to' => AddressHeader,
'resent-to' => AddressHeader,
'resent-cc' => AddressHeader,
'resent-bcc' => AddressHeader,
'resent-from' => AddressHeader,
'resent-reply-to' => AddressHeader,
'sender' => SingleAddressHeader,
'resent-sender' => SingleAddressHeader,
'return-path' => ReturnPathHeader,
'message-id' => MessageIdHeader,
'resent-message-id' => MessageIdHeader,
'in-reply-to' => ReferencesHeader,
'received' => ReceivedHeader,
'references' => ReferencesHeader,
'keywords' => KeywordsHeader,
'encrypted' => EncryptedHeader,
'mime-version' => MimeVersionHeader,
'content-type' => ContentTypeHeader,
'content-transfer-encoding' => ContentTransferEncodingHeader,
'content-disposition' => ContentDispositionHeader,
'content-id' => MessageIdHeader,
'subject' => UnstructuredHeader,
'comments' => UnstructuredHeader,
'content-description' => UnstructuredHeader
}
end
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb | # scanner_r.rb
#
#--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
require 'tmail/config'
module TMail
class TMailScanner
Version = '1.2.3'
Version.freeze
MIME_HEADERS = {
:CTYPE => true,
:CENCODING => true,
:CDISPOSITION => true
}
alnum = 'a-zA-Z0-9'
atomsyms = %q[ _#!$%&`'*+-{|}~^/=? ].strip
tokensyms = %q[ _#!$%&`'*+-{|}~^@. ].strip
atomchars = alnum + Regexp.quote(atomsyms)
tokenchars = alnum + Regexp.quote(tokensyms)
iso2022str = '\e(?!\(B)..(?:[^\e]+|\e(?!\(B)..)*\e\(B'
eucstr = "(?:[\xa1-\xfe][\xa1-\xfe])+"
sjisstr = "(?:[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc])+"
utf8str = "(?:[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf])+"
quoted_with_iso2022 = /\A(?:[^\\\e"]+|#{iso2022str})+/n
domlit_with_iso2022 = /\A(?:[^\\\e\]]+|#{iso2022str})+/n
comment_with_iso2022 = /\A(?:[^\\\e()]+|#{iso2022str})+/n
quoted_without_iso2022 = /\A[^\\"]+/n
domlit_without_iso2022 = /\A[^\\\]]+/n
comment_without_iso2022 = /\A[^\\()]+/n
PATTERN_TABLE = {}
PATTERN_TABLE['EUC'] =
[
/\A(?:[#{atomchars}]+|#{iso2022str}|#{eucstr})+/n,
/\A(?:[#{tokenchars}]+|#{iso2022str}|#{eucstr})+/n,
quoted_with_iso2022,
domlit_with_iso2022,
comment_with_iso2022
]
PATTERN_TABLE['SJIS'] =
[
/\A(?:[#{atomchars}]+|#{iso2022str}|#{sjisstr})+/n,
/\A(?:[#{tokenchars}]+|#{iso2022str}|#{sjisstr})+/n,
quoted_with_iso2022,
domlit_with_iso2022,
comment_with_iso2022
]
PATTERN_TABLE['UTF8'] =
[
/\A(?:[#{atomchars}]+|#{utf8str})+/n,
/\A(?:[#{tokenchars}]+|#{utf8str})+/n,
quoted_without_iso2022,
domlit_without_iso2022,
comment_without_iso2022
]
PATTERN_TABLE['NONE'] =
[
/\A[#{atomchars}]+/n,
/\A[#{tokenchars}]+/n,
quoted_without_iso2022,
domlit_without_iso2022,
comment_without_iso2022
]
def initialize( str, scantype, comments )
init_scanner str
@comments = comments || []
@debug = false
# fix scanner mode
@received = (scantype == :RECEIVED)
@is_mime_header = MIME_HEADERS[scantype]
atom, token, @quoted_re, @domlit_re, @comment_re = PATTERN_TABLE[TMail.KCODE]
@word_re = (MIME_HEADERS[scantype] ? token : atom)
end
attr_accessor :debug
def scan( &block )
if @debug
scan_main do |arr|
s, v = arr
printf "%7d %-10s %s\n",
rest_size(),
s.respond_to?(:id2name) ? s.id2name : s.inspect,
v.inspect
yield arr
end
else
scan_main(&block)
end
end
private
RECV_TOKEN = {
'from' => :FROM,
'by' => :BY,
'via' => :VIA,
'with' => :WITH,
'id' => :ID,
'for' => :FOR
}
def scan_main
until eof?
if skip(/\A[\n\r\t ]+/n) # LWSP
break if eof?
end
if s = readstr(@word_re)
if @is_mime_header
yield [:TOKEN, s]
else
# atom
if /\A\d+\z/ === s
yield [:DIGIT, s]
elsif @received
yield [RECV_TOKEN[s.downcase] || :ATOM, s]
else
yield [:ATOM, s]
end
end
elsif skip(/\A"/)
yield [:QUOTED, scan_quoted_word()]
elsif skip(/\A\[/)
yield [:DOMLIT, scan_domain_literal()]
elsif skip(/\A\(/)
@comments.push scan_comment()
else
c = readchar()
yield [c, c]
end
end
yield [false, '$']
end
def scan_quoted_word
scan_qstr(@quoted_re, /\A"/, 'quoted-word')
end
def scan_domain_literal
'[' + scan_qstr(@domlit_re, /\A\]/, 'domain-literal') + ']'
end
def scan_qstr( pattern, terminal, type )
result = ''
until eof?
if s = readstr(pattern) then result << s
elsif skip(terminal) then return result
elsif skip(/\A\\/) then result << readchar()
else
raise "TMail FATAL: not match in #{type}"
end
end
scan_error! "found unterminated #{type}"
end
def scan_comment
result = ''
nest = 1
content = @comment_re
until eof?
if s = readstr(content) then result << s
elsif skip(/\A\)/) then nest -= 1
return result if nest == 0
result << ')'
elsif skip(/\A\(/) then nest += 1
result << '('
elsif skip(/\A\\/) then result << readchar()
else
raise 'TMail FATAL: not match in comment'
end
end
scan_error! 'found unterminated comment'
end
# string scanner
def init_scanner( str )
@src = str
end
def eof?
@src.empty?
end
def rest_size
@src.size
end
def readstr( re )
if m = re.match(@src)
@src = m.post_match
m[0]
else
nil
end
end
def readchar
readstr(/\A./)
end
def skip( re )
if m = re.match(@src)
@src = m.post_match
true
else
false
end
end
def scan_error!( msg )
raise SyntaxError, msg
end
end
end # module TMail
#:startdoc: | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb | provider/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb | #--
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
require 'nkf'
#:startdoc:
module TMail
class Mail
def send_to( smtp )
do_send_to(smtp) do
ready_to_send
end
end
def send_text_to( smtp )
do_send_to(smtp) do
ready_to_send
mime_encode
end
end
def do_send_to( smtp )
from = from_address or raise ArgumentError, 'no from address'
(dests = destinations).empty? and raise ArgumentError, 'no receipient'
yield
send_to_0 smtp, from, dests
end
private :do_send_to
def send_to_0( smtp, from, to )
smtp.ready(from, to) do |f|
encoded "\r\n", 'j', f, ''
end
end
def ready_to_send
delete_no_send_fields
add_message_id
add_date
end
NOSEND_FIELDS = %w(
received
bcc
)
def delete_no_send_fields
NOSEND_FIELDS.each do |nm|
delete nm
end
delete_if {|n,v| v.empty? }
end
def add_message_id( fqdn = nil )
self.message_id = ::TMail::new_message_id(fqdn)
end
def add_date
self.date = Time.now
end
def mime_encode
if parts.empty?
mime_encode_singlepart
else
mime_encode_multipart true
end
end
def mime_encode_singlepart
self.mime_version = '1.0'
b = body
if NKF.guess(b) != NKF::BINARY
mime_encode_text b
else
mime_encode_binary b
end
end
def mime_encode_text( body )
self.body = NKF.nkf('-j -m0', body)
self.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
self.encoding = '7bit'
end
def mime_encode_binary( body )
self.body = [body].pack('m')
self.set_content_type 'application', 'octet-stream'
self.encoding = 'Base64'
end
def mime_encode_multipart( top = true )
self.mime_version = '1.0' if top
self.set_content_type 'multipart', 'mixed'
e = encoding(nil)
if e and not /\A(?:7bit|8bit|binary)\z/i === e
raise ArgumentError,
'using C.T.Encoding with multipart mail is not permitted'
end
end
end
#:stopdoc:
class DeleteFields
NOSEND_FIELDS = %w(
received
bcc
)
def initialize( nosend = nil, delempty = true )
@no_send_fields = nosend || NOSEND_FIELDS.dup
@delete_empty_fields = delempty
end
attr :no_send_fields
attr :delete_empty_fields, true
def exec( mail )
@no_send_fields.each do |nm|
delete nm
end
delete_if {|n,v| v.empty? } if @delete_empty_fields
end
end
#:startdoc:
#:stopdoc:
class AddMessageId
def initialize( fqdn = nil )
@fqdn = fqdn
end
attr :fqdn, true
def exec( mail )
mail.message_id = ::TMail::new_msgid(@fqdn)
end
end
#:startdoc:
#:stopdoc:
class AddDate
def exec( mail )
mail.date = Time.now
end
end
#:startdoc:
#:stopdoc:
class MimeEncodeAuto
def initialize( s = nil, m = nil )
@singlepart_composer = s || MimeEncodeSingle.new
@multipart_composer = m || MimeEncodeMulti.new
end
attr :singlepart_composer
attr :multipart_composer
def exec( mail )
if mail._builtin_multipart?
then @multipart_composer
else @singlepart_composer end.exec mail
end
end
#:startdoc:
#:stopdoc:
class MimeEncodeSingle
def exec( mail )
mail.mime_version = '1.0'
b = mail.body
if NKF.guess(b) != NKF::BINARY
on_text b
else
on_binary b
end
end
def on_text( body )
mail.body = NKF.nkf('-j -m0', body)
mail.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
mail.encoding = '7bit'
end
def on_binary( body )
mail.body = [body].pack('m')
mail.set_content_type 'application', 'octet-stream'
mail.encoding = 'Base64'
end
end
#:startdoc:
#:stopdoc:
class MimeEncodeMulti
def exec( mail, top = true )
mail.mime_version = '1.0' if top
mail.set_content_type 'multipart', 'mixed'
e = encoding(nil)
if e and not /\A(?:7bit|8bit|binary)\z/i === e
raise ArgumentError,
'using C.T.Encoding with multipart mail is not permitted'
end
mail.parts.each do |m|
exec m, false if m._builtin_multipart?
end
end
end
#:startdoc:
end # module TMail
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/activesupport.rb | provider/vendor/rails/activesupport/lib/activesupport.rb | require 'active_support'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support.rb | provider/vendor/rails/activesupport/lib/active_support.rb | #--
# Copyright (c) 2005 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module ActiveSupport
def self.load_all!
[Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone]
end
autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
autoload :Base64, 'active_support/base64'
autoload :BasicObject, 'active_support/basic_object'
autoload :BufferedLogger, 'active_support/buffered_logger'
autoload :Cache, 'active_support/cache'
autoload :Callbacks, 'active_support/callbacks'
autoload :Deprecation, 'active_support/deprecation'
autoload :Duration, 'active_support/duration'
autoload :Gzip, 'active_support/gzip'
autoload :Inflector, 'active_support/inflector'
autoload :Memoizable, 'active_support/memoizable'
autoload :MessageEncryptor, 'active_support/message_encryptor'
autoload :MessageVerifier, 'active_support/message_verifier'
autoload :Multibyte, 'active_support/multibyte'
autoload :OptionMerger, 'active_support/option_merger'
autoload :OrderedHash, 'active_support/ordered_hash'
autoload :OrderedOptions, 'active_support/ordered_options'
autoload :Rescuable, 'active_support/rescuable'
autoload :SecureRandom, 'active_support/secure_random'
autoload :StringInquirer, 'active_support/string_inquirer'
autoload :TimeWithZone, 'active_support/time_with_zone'
autoload :TimeZone, 'active_support/values/time_zone'
autoload :XmlMini, 'active_support/xml_mini'
end
require 'active_support/vendor'
require 'active_support/core_ext'
require 'active_support/dependencies'
require 'active_support/json'
I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/ordered_hash.rb | provider/vendor/rails/activesupport/lib/active_support/ordered_hash.rb | # OrderedHash is namespaced to prevent conflicts with other implementations
module ActiveSupport
# Hash is ordered in Ruby 1.9!
if RUBY_VERSION >= '1.9'
OrderedHash = ::Hash
else
class OrderedHash < Hash #:nodoc:
def initialize(*args, &block)
super
@keys = []
end
def self.[](*args)
ordered_hash = new
if (args.length == 1 && args.first.is_a?(Array))
args.first.each do |key_value_pair|
next unless (key_value_pair.is_a?(Array))
ordered_hash[key_value_pair[0]] = key_value_pair[1]
end
return ordered_hash
end
unless (args.size % 2 == 0)
raise ArgumentError.new("odd number of arguments for Hash")
end
args.each_with_index do |val, ind|
next if (ind % 2 != 0)
ordered_hash[val] = args[ind + 1]
end
ordered_hash
end
def initialize_copy(other)
super
# make a deep copy of keys
@keys = other.keys
end
def []=(key, value)
@keys << key if !has_key?(key)
super
end
def delete(key)
if has_key? key
index = @keys.index(key)
@keys.delete_at index
end
super
end
def delete_if
super
sync_keys!
self
end
def reject!
super
sync_keys!
self
end
def reject(&block)
dup.reject!(&block)
end
def keys
@keys.dup
end
def values
@keys.collect { |key| self[key] }
end
def to_hash
self
end
def to_a
@keys.map { |key| [ key, self[key] ] }
end
def each_key
@keys.each { |key| yield key }
end
def each_value
@keys.each { |key| yield self[key]}
end
def each
@keys.each {|key| yield [key, self[key]]}
end
alias_method :each_pair, :each
def clear
super
@keys.clear
self
end
def shift
k = @keys.first
v = delete(k)
[k, v]
end
def merge!(other_hash)
other_hash.each {|k,v| self[k] = v }
self
end
def merge(other_hash)
dup.merge!(other_hash)
end
def inspect
"#<OrderedHash #{super}>"
end
private
def sync_keys!
@keys.delete_if {|k| !has_key?(k)}
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/time_with_zone.rb | provider/vendor/rails/activesupport/lib/active_support/time_with_zone.rb | require 'tzinfo'
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
# limited to UTC and the system's <tt>ENV['TZ']</tt> zone.
#
# You shouldn't ever need to create a TimeWithZone instance directly via <tt>new</tt> -- instead, Rails provides the methods
# +local+, +parse+, +at+ and +now+ on TimeZone instances, and +in_time_zone+ on Time and DateTime instances, for a more
# user-friendly syntax. Examples:
#
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.parse('2007-02-01 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
#
# See TimeZone and ActiveSupport::CoreExtensions::Time::Zones for further documentation for these methods.
#
# TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangable. Examples:
#
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
# t.hour # => 13
# t.dst? # => true
# t.utc_offset # => -14400
# t.zone # => "EDT"
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
# t > Time.utc(1999) # => true
# t.is_a?(Time) # => true
# t.is_a?(ActiveSupport::TimeWithZone) # => true
class TimeWithZone
include Comparable
attr_reader :time_zone
def initialize(utc_time, time_zone, local_time = nil, period = nil)
@utc, @time_zone, @time = utc_time, time_zone, local_time
@period = @utc ? period : get_period_and_ensure_valid_local_time
end
# Returns a Time or DateTime instance that represents the time in +time_zone+.
def time
@time ||= period.to_local(@utc)
end
# Returns a Time or DateTime instance that represents the time in UTC.
def utc
@utc ||= period.to_utc(@time)
end
alias_method :comparable_time, :utc
alias_method :getgm, :utc
alias_method :getutc, :utc
alias_method :gmtime, :utc
# Returns the underlying TZInfo::TimezonePeriod.
def period
@period ||= time_zone.period_for_utc(@utc)
end
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
def in_time_zone(new_zone = ::Time.zone)
return self if time_zone == new_zone
utc.in_time_zone(new_zone)
end
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone
def localtime
utc.getlocal
end
alias_method :getlocal, :localtime
def dst?
period.dst?
end
alias_method :isdst, :dst?
def utc?
time_zone.name == 'UTC'
end
alias_method :gmt?, :utc?
def utc_offset
period.utc_total_offset
end
alias_method :gmt_offset, :utc_offset
alias_method :gmtoff, :utc_offset
def formatted_offset(colon = true, alternate_utc_string = nil)
utc? && alternate_utc_string || utc_offset.to_utc_offset_s(colon)
end
# Time uses +zone+ to display the time zone abbreviation, so we're duck-typing it.
def zone
period.zone_identifier.to_s
end
def inspect
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
end
def xmlschema(fraction_digits = 0)
fraction = if fraction_digits > 0
".%i" % time.usec.to_s[0, fraction_digits]
end
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
end
alias_method :iso8601, :xmlschema
# Coerces the date to a string for JSON encoding.
#
# ISO 8601 format is used if ActiveSupport::JSON::Encoding.use_standard_json_time_format is set.
#
# ==== Examples
#
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
# # => "2005-02-01T15:15:10Z"
#
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
# # => "2005/02/01 15:15:10 +0000"
def as_json(options = nil)
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
def to_yaml(options = {})
if options.kind_of?(YAML::Emitter)
utc.to_yaml(options)
else
time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z'))
end
end
def httpdate
utc.httpdate
end
def rfc2822
to_s(:rfc822)
end
alias_method :rfc822, :rfc2822
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
def to_s(format = :default)
return utc.to_s(format) if format == :db
if formatter = ::Time::DATE_FORMATS[format]
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
else
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
end
end
alias_method :to_formatted_s, :to_s
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
# Time#strftime, so that zone information is correct
def strftime(format)
format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false))
time.strftime(format)
end
# Use the time in UTC for comparisons.
def <=>(other)
utc <=> other
end
def between?(min, max)
utc.between?(min, max)
end
def past?
utc.past?
end
def today?
time.today?
end
def future?
utc.future?
end
def eql?(other)
utc == other
end
def +(other)
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
if duration_of_variable_length?(other)
method_missing(:+, other)
else
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
result.in_time_zone(time_zone)
end
end
def -(other)
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
if other.acts_like?(:time)
utc.to_f - other.to_f
elsif duration_of_variable_length?(other)
method_missing(:-, other)
else
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
result.in_time_zone(time_zone)
end
end
def since(other)
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
if duration_of_variable_length?(other)
method_missing(:since, other)
else
utc.since(other).in_time_zone(time_zone)
end
end
def ago(other)
since(-other)
end
def advance(options)
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
# otherwise advance from #utc, for accuracy when moving across DST boundaries
if options.values_at(:years, :weeks, :months, :days).any?
method_missing(:advance, options)
else
utc.advance(options).in_time_zone(time_zone)
end
end
%w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
class_eval <<-EOV
def #{method_name} # def year
time.#{method_name} # time.year
end # end
EOV
end
def usec
time.respond_to?(:usec) ? time.usec : 0
end
def to_a
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
end
def to_f
utc.to_f
end
def to_i
utc.to_i
end
alias_method :hash, :to_i
alias_method :tv_sec, :to_i
# A TimeWithZone acts like a Time, so just return +self+.
def to_time
self
end
def to_datetime
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
end
# So that +self+ <tt>acts_like?(:time)</tt>.
def acts_like_time?
true
end
# Say we're a Time to thwart type checking.
def is_a?(klass)
klass == ::Time || super
end
alias_method :kind_of?, :is_a?
def freeze
period; utc; time # preload instance variables before freezing
super
end
def marshal_dump
[utc, time_zone.name, time]
end
def marshal_load(variables)
initialize(variables[0].utc, ::Time.__send__(:get_zone, variables[1]), variables[2].utc)
end
# Ensure proxy class responds to all methods that underlying time instance responds to.
def respond_to?(sym, include_priv = false)
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
return false if sym.to_s == 'acts_like_date?'
super || time.respond_to?(sym, include_priv)
end
# Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+.
def method_missing(sym, *args, &block)
result = time.__send__(sym, *args, &block)
result.acts_like?(:time) ? self.class.new(nil, time_zone, result) : result
end
private
def get_period_and_ensure_valid_local_time
# we don't want a Time.local instance enforcing its own DST rules as well,
# so transfer time values to a utc constructor if necessary
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
begin
@time_zone.period_for_local(@time)
rescue ::TZInfo::PeriodNotFound
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
@time += 1.hour
retry
end
end
def transfer_time_values_to_utc_constructor(time)
::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, time.respond_to?(:usec) ? time.usec : 0)
end
def duration_of_variable_length?(obj)
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include? p[0] }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/ordered_options.rb | provider/vendor/rails/activesupport/lib/active_support/ordered_options.rb | module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash #:nodoc:
def []=(key, value)
super(key.to_sym, value)
end
def [](key)
super(key.to_sym)
end
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
self[$1.to_sym] = args.first
else
self[name]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/test_case.rb | provider/vendor/rails/activesupport/lib/active_support/test_case.rb | require 'test/unit/testcase'
require 'active_support/testing/setup_and_teardown'
require 'active_support/testing/assertions'
require 'active_support/testing/deprecation'
require 'active_support/testing/declarative'
begin
gem 'mocha', ">= 0.9.7"
require 'mocha'
rescue LoadError
# Fake Mocha::ExpectationError so we can rescue it in #run. Bleh.
Object.const_set :Mocha, Module.new
Mocha.const_set :ExpectationError, Class.new(StandardError)
end
module ActiveSupport
class TestCase < ::Test::Unit::TestCase
if defined? MiniTest
Assertion = MiniTest::Assertion
alias_method :method_name, :name if method_defined? :name
alias_method :method_name, :__name__ if method_defined? :__name__
else
# TODO: Figure out how to get the Rails::BacktraceFilter into minitest/unit
if defined?(Rails) && ENV['BACKTRACE'].nil?
require 'rails/backtrace_cleaner'
Test::Unit::Util::BacktraceFilter.module_eval { include Rails::BacktraceFilterForTestUnit }
end
Assertion = Test::Unit::AssertionFailedError
require 'active_support/testing/default'
include ActiveSupport::Testing::Default
end
include ActiveSupport::Testing::SetupAndTeardown
include ActiveSupport::Testing::Assertions
include ActiveSupport::Testing::Deprecation
extend ActiveSupport::Testing::Declarative
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/deprecation.rb | provider/vendor/rails/activesupport/lib/active_support/deprecation.rb | require 'yaml'
module ActiveSupport
module Deprecation #:nodoc:
mattr_accessor :debug
self.debug = false
# Choose the default warn behavior according to RAILS_ENV.
# Ignore deprecation warnings in production.
DEFAULT_BEHAVIORS = {
'test' => Proc.new { |message, callstack|
$stderr.puts(message)
$stderr.puts callstack.join("\n ") if debug
},
'development' => Proc.new { |message, callstack|
logger = defined?(Rails) ? Rails.logger : Logger.new($stderr)
logger.warn message
logger.debug callstack.join("\n ") if debug
}
}
class << self
def warn(message = nil, callstack = caller)
behavior.call(deprecation_message(callstack, message), callstack) if behavior && !silenced?
end
def default_behavior
if defined?(RAILS_ENV)
DEFAULT_BEHAVIORS[RAILS_ENV.to_s]
else
DEFAULT_BEHAVIORS['test']
end
end
# Have deprecations been silenced?
def silenced?
@silenced = false unless defined?(@silenced)
@silenced
end
# Silence deprecation warnings within the block.
def silence
old_silenced, @silenced = @silenced, true
yield
ensure
@silenced = old_silenced
end
attr_writer :silenced
private
def deprecation_message(callstack, message = nil)
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
"DEPRECATION WARNING: #{message}. #{deprecation_caller_message(callstack)}"
end
def deprecation_caller_message(callstack)
file, line, method = extract_callstack(callstack)
if file
if line && method
"(called from #{method} at #{file}:#{line})"
else
"(called from #{file}:#{line})"
end
end
end
def extract_callstack(callstack)
if md = callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
md.captures
else
callstack.first
end
end
end
# Behavior is a block that takes a message argument.
mattr_accessor :behavior
self.behavior = default_behavior
# Warnings are not silenced by default.
self.silenced = false
module ClassMethods #:nodoc:
# Declare that a method has been deprecated.
def deprecate(*method_names)
options = method_names.extract_options!
method_names = method_names + options.keys
method_names.each do |method_name|
alias_method_chain(method_name, :deprecation) do |target, punctuation|
class_eval(<<-EOS, __FILE__, __LINE__)
def #{target}_with_deprecation#{punctuation}(*args, &block) # def generate_secret_with_deprecation(*args, &block)
::ActiveSupport::Deprecation.warn( # ::ActiveSupport::Deprecation.warn(
self.class.deprecated_method_warning( # self.class.deprecated_method_warning(
:#{method_name}, # :generate_secret,
#{options[method_name].inspect}), # "You should use ActiveSupport::SecureRandom.hex(64)"),
caller # caller
) # )
send(:#{target}_without_deprecation#{punctuation}, *args, &block) # send(:generate_secret_without_deprecation, *args, &block)
end # end
EOS
end
end
end
def deprecated_method_warning(method_name, message=nil)
warning = "#{method_name} is deprecated and will be removed from Rails #{deprecation_horizon}"
case message
when Symbol then "#{warning} (use #{message} instead)"
when String then "#{warning} (#{message})"
else warning
end
end
def deprecation_horizon
'2.3'
end
end
class DeprecationProxy #:nodoc:
silence_warnings do
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end
# Don't give a deprecation warning on inspect since test/unit and error
# logs rely on it for diagnostics.
def inspect
target.inspect
end
private
def method_missing(called, *args, &block)
warn caller, called, args
target.__send__(called, *args, &block)
end
end
class DeprecatedObjectProxy < DeprecationProxy
def initialize(object, message)
@object = object
@message = message
end
private
def target
@object
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn(@message, callstack)
end
end
# Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc.
# which emits deprecation warnings on any method call (except +inspect+).
class DeprecatedInstanceVariableProxy < DeprecationProxy #:nodoc:
def initialize(instance, method, var = "@#{method}")
@instance, @method, @var = instance, method, var
end
private
def target
@instance.__send__(@method)
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
end
end
class DeprecatedConstantProxy < DeprecationProxy #:nodoc:
def initialize(old_const, new_const)
@old_const = old_const
@new_const = new_const
end
def class
target.class
end
private
def target
@new_const.to_s.constantize
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
end
end
end
end
class Module
include ActiveSupport::Deprecation::ClassMethods
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/vendor.rb | provider/vendor/rails/activesupport/lib/active_support/vendor.rb | # Prefer gems to the bundled libs.
require 'rubygems'
begin
gem 'builder', '~> 2.1.2'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/builder-2.1.2"
end
require 'builder'
begin
gem 'memcache-client', '>= 1.7.4'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.7.4"
end
begin
gem 'tzinfo', '~> 0.3.12'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.12"
end
begin
gem 'i18n', '~> 0.1.3'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/i18n-0.1.3/lib"
require 'i18n'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/version.rb | provider/vendor/rails/activesupport/lib/active_support/version.rb | module ActiveSupport
module VERSION #:nodoc:
MAJOR = 2
MINOR = 3
TINY = 4
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/rescuable.rb | provider/vendor/rails/activesupport/lib/active_support/rescuable.rb | module ActiveSupport
# Rescuable module adds support for easier exception handling.
module Rescuable
def self.included(base) # :nodoc:
base.class_inheritable_accessor :rescue_handlers
base.rescue_handlers = []
base.extend(ClassMethods)
end
module ClassMethods
# Rescue exceptions raised in controller actions.
#
# <tt>rescue_from</tt> receives a series of exception classes or class
# names, and a trailing <tt>:with</tt> option with the name of a method
# or a Proc object to be called to handle them. Alternatively a block can
# be given.
#
# Handlers that take one argument will be called with the exception, so
# that the exception can be inspected when dealing with it.
#
# Handlers are inherited. They are searched from right to left, from
# bottom to top, and up the hierarchy. The handler of the first class for
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
# any.
#
# class ApplicationController < ActionController::Base
# rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
# rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
#
# rescue_from 'MyAppError::Base' do |exception|
# render :xml => exception, :status => 500
# end
#
# protected
# def deny_access
# ...
# end
#
# def show_errors(exception)
# exception.record.new_record? ? ...
# end
# end
def rescue_from(*klasses, &block)
options = klasses.extract_options!
unless options.has_key?(:with)
if block_given?
options[:with] = block
else
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
end
end
klasses.each do |klass|
key = if klass.is_a?(Class) && klass <= Exception
klass.name
elsif klass.is_a?(String)
klass
else
raise ArgumentError, "#{klass} is neither an Exception nor a String"
end
# put the new handler at the end because the list is read in reverse
rescue_handlers << [key, options[:with]]
end
end
end
# Tries to rescue the exception by looking up and calling a registered handler.
def rescue_with_handler(exception)
if handler = handler_for_rescue(exception)
handler.arity != 0 ? handler.call(exception) : handler.call
true # don't rely on the return value of the handler
end
end
def handler_for_rescue(exception)
# We go from right to left because pairs are pushed onto rescue_handlers
# as rescue_from declarations are found.
_, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
# The purpose of allowing strings in rescue_from is to support the
# declaration of handler associations for exception classes whose
# definition is yet unknown.
#
# Since this loop needs the constants it would be inconsistent to
# assume they should exist at this point. An early raised exception
# could trigger some other handler and the array could include
# precisely a string whose corresponding constant has not yet been
# seen. This is why we are tolerant to unknown constants.
#
# Note that this tolerance only matters if the exception was given as
# a string, otherwise a NameError will be raised by the interpreter
# itself when rescue_from CONSTANT is executed.
klass = self.class.const_get(klass_name) rescue nil
klass ||= klass_name.constantize rescue nil
exception.is_a?(klass) if klass
end
case rescuer
when Symbol
method(rescuer)
when Proc
rescuer.bind(self)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/duration.rb | provider/vendor/rails/activesupport/lib/active_support/duration.rb | require 'active_support/basic_object'
module ActiveSupport
# Provides accurate date and time measurements using Date#advance and
# Time#advance, respectively. It mainly supports the methods on Numeric,
# such as in this example:
#
# 1.month.ago # equivalent to Time.now.advance(:months => -1)
class Duration < BasicObject
attr_accessor :value, :parts
def initialize(value, parts) #:nodoc:
@value, @parts = value, parts
end
# Adds another Duration or a Numeric to this Duration. Numeric values
# are treated as seconds.
def +(other)
if Duration === other
Duration.new(value + other.value, @parts + other.parts)
else
Duration.new(value + other, @parts + [[:seconds, other]])
end
end
# Subtracts another Duration or a Numeric from this Duration. Numeric
# values are treated as seconds.
def -(other)
self + (-other)
end
def -@ #:nodoc:
Duration.new(-value, parts.map { |type,number| [type, -number] })
end
def is_a?(klass) #:nodoc:
klass == Duration || super
end
# Returns true if <tt>other</tt> is also a Duration instance with the
# same <tt>value</tt>, or if <tt>other == value</tt>.
def ==(other)
if Duration === other
other.value == value
else
other == value
end
end
def self.===(other) #:nodoc:
other.is_a?(Duration) rescue super
end
# Calculates a new Time or Date that is as far in the future
# as this Duration represents.
def since(time = ::Time.current)
sum(1, time)
end
alias :from_now :since
# Calculates a new Time or Date that is as far in the past
# as this Duration represents.
def ago(time = ::Time.current)
sum(-1, time)
end
alias :until :ago
def inspect #:nodoc:
consolidated = parts.inject(::Hash.new(0)) { |h,part| h[part.first] += part.last; h }
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
n = consolidated[length]
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
end.compact
parts = ["0 seconds"] if parts.empty?
parts.to_sentence(:locale => :en)
end
protected
def sum(sign, time = ::Time.current) #:nodoc:
parts.inject(time) do |t,(type,number)|
if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
else
t.advance(type => sign * number)
end
else
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
end
end
end
private
def method_missing(method, *args, &block) #:nodoc:
value.send(method, *args)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/core_ext.rb | provider/vendor/rails/activesupport/lib/active_support/core_ext.rb | Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].sort.each do |path|
filename = File.basename(path, '.rb')
require "active_support/core_ext/#{filename}"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/xml_mini.rb | provider/vendor/rails/activesupport/lib/active_support/xml_mini.rb | module ActiveSupport
# = XmlMini
#
# To use the much faster libxml parser:
# gem 'libxml-ruby', '=0.9.7'
# XmlMini.backend = 'LibXML'
module XmlMini
extend self
attr_reader :backend
delegate :parse, :to => :backend
def backend=(name)
if name.is_a?(Module)
@backend = name
else
require "active_support/xml_mini/#{name.to_s.downcase}.rb"
@backend = ActiveSupport.const_get("XmlMini_#{name}")
end
end
def with_backend(name)
old_backend, self.backend = backend, name
yield
ensure
self.backend = old_backend
end
end
XmlMini.backend = 'REXML'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/message_verifier.rb | provider/vendor/rails/activesupport/lib/active_support/message_verifier.rb | module ActiveSupport
# MessageVerifier makes it easy to generate and verify messages which are signed
# to prevent tampering.
#
# This is useful for cases like remember-me tokens and auto-unsubscribe links where the
# session store isn't suitable or available.
#
# Remember Me:
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
#
# In the authentication filter:
#
# id, time = @verifier.verify(cookies[:remember_me])
# if time < Time.now
# self.current_user = User.find(id)
# end
#
class MessageVerifier
class InvalidSignature < StandardError; end
def initialize(secret, digest = 'SHA1')
@secret = secret
@digest = digest
end
def verify(signed_message)
data, digest = signed_message.split("--")
if secure_compare(digest, generate_digest(data))
Marshal.load(ActiveSupport::Base64.decode64(data))
else
raise InvalidSignature
end
end
def generate(value)
data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
"#{data}--#{generate_digest(data)}"
end
private
# constant-time comparison algorithm to prevent timing attacks
def secure_compare(a, b)
if a.length == b.length
result = 0
for i in 0..(a.length - 1)
result |= a[i] ^ b[i]
end
result == 0
else
false
end
end
def generate_digest(data)
require 'openssl' unless defined?(OpenSSL)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), @secret, data)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/inflector.rb | provider/vendor/rails/activesupport/lib/active_support/inflector.rb | # encoding: utf-8
require 'singleton'
require 'iconv'
module ActiveSupport
# The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
# and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
# in inflections.rb.
#
# The Rails core team has stated patches for the inflections library will not be accepted
# in order to avoid breaking legacy applications which may be relying on errant inflections.
# If you discover an incorrect inflection and require it for your application, you'll need
# to correct it yourself (explained below).
module Inflector
extend self
# A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
# inflection rules. Examples:
#
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1\2en'
# inflect.singular /^(ox)en/i, '\1'
#
# inflect.irregular 'octopus', 'octopi'
#
# inflect.uncountable "equipment"
# end
#
# New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the
# pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
# already have been loaded.
class Inflections
include Singleton
attr_reader :plurals, :singulars, :uncountables, :humans
def initialize
@plurals, @singulars, @uncountables, @humans = [], [], [], []
end
# Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
# The replacement should always be a string that may include references to the matched data from the rule.
def plural(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@plurals.insert(0, [rule, replacement])
end
# Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
# The replacement should always be a string that may include references to the matched data from the rule.
def singular(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@singulars.insert(0, [rule, replacement])
end
# Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
# for strings, not regular expressions. You simply pass the irregular in singular and plural form.
#
# Examples:
# irregular 'octopus', 'octopi'
# irregular 'person', 'people'
def irregular(singular, plural)
@uncountables.delete(singular)
@uncountables.delete(plural)
if singular[0,1].upcase == plural[0,1].upcase
plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
else
plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
end
end
# Add uncountable words that shouldn't be attempted inflected.
#
# Examples:
# uncountable "money"
# uncountable "money", "information"
# uncountable %w( money information rice )
def uncountable(*words)
(@uncountables << words).flatten!
end
# Specifies a humanized form of a string by a regular expression rule or by a string mapping.
# When using a regular expression based replacement, the normal humanize formatting is called after the replacement.
# When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name')
#
# Examples:
# human /_cnt$/i, '\1_count'
# human "legacy_col_person_name", "Name"
def human(rule, replacement)
@humans.insert(0, [rule, replacement])
end
# Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
# Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
# <tt>:singulars</tt>, <tt>:uncountables</tt>, <tt>:humans</tt>.
#
# Examples:
# clear :all
# clear :plurals
def clear(scope = :all)
case scope
when :all
@plurals, @singulars, @uncountables = [], [], []
else
instance_variable_set "@#{scope}", []
end
end
end
# Yields a singleton instance of Inflector::Inflections so you can specify additional
# inflector rules.
#
# Example:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.uncountable "rails"
# end
def inflections
if block_given?
yield Inflections.instance
else
Inflections.instance
end
end
# Returns the plural form of the word in the string.
#
# Examples:
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word)
result = word.to_s.dup
if word.empty? || inflections.uncountables.include?(result.downcase)
result
else
inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result
end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
#
# Examples:
# "posts".singularize # => "post"
# "octopi".singularize # => "octopus"
# "sheep".singluarize # => "sheep"
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
result = word.to_s.dup
if inflections.uncountables.include?(result.downcase)
result
else
inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result
end
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
# is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
#
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
#
# Examples:
# "active_record".camelize # => "ActiveRecord"
# "active_record".camelize(:lower) # => "activeRecord"
# "active_record/errors".camelize # => "ActiveRecord::Errors"
# "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
if first_letter_in_uppercase
lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
lower_case_and_underscored_word.first.downcase + camelize(lower_case_and_underscored_word)[1..-1]
end
end
# Capitalizes all the words and replaces some characters in the string to create
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
# used in the Rails internals.
#
# +titleize+ is also aliased as as +titlecase+.
#
# Examples:
# "man from the boondocks".titleize # => "Man From The Boondocks"
# "x-men: the last stand".titleize # => "X Men: The Last Stand"
def titleize(word)
humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
#
# Changes '::' to '/' to convert namespaces to paths.
#
# Examples:
# "ActiveRecord".underscore # => "active_record"
# "ActiveRecord::Errors".underscore # => active_record/errors
def underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
# Replaces underscores with dashes in the string.
#
# Example:
# "puni_puni" # => "puni-puni"
def dasherize(underscored_word)
underscored_word.gsub(/_/, '-')
end
# Capitalizes the first word and turns underscores into spaces and strips a
# trailing "_id", if any. Like +titleize+, this is meant for creating pretty output.
#
# Examples:
# "employee_salary" # => "Employee salary"
# "author_id" # => "Author"
def humanize(lower_case_and_underscored_word)
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end
# Removes the module part from the expression in the string.
#
# Examples:
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
# "Inflections".demodulize # => "Inflections"
def demodulize(class_name_in_module)
class_name_in_module.to_s.gsub(/^.*::/, '')
end
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
#
# ==== Examples
#
# class Person
# def to_param
# "#{id}-#{name.parameterize}"
# end
# end
#
# @person = Person.find(1)
# # => #<Person id: 1, name: "Donald E. Knuth">
#
# <%= link_to(@person.name, person_path(@person)) %>
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
def parameterize(string, sep = '-')
# replace accented chars with ther ascii equivalents
parameterized_string = transliterate(string)
# Turn unwanted chars into the seperator
parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep)
unless sep.blank?
re_sep = Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
end
parameterized_string.downcase
end
# Replaces accented characters with their ascii equivalents.
def transliterate(string)
Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s
end
if RUBY_VERSION >= '1.9'
undef_method :transliterate
def transliterate(string)
warn "Ruby 1.9 doesn't support Unicode normalization yet"
string.dup
end
# The iconv transliteration code doesn't function correctly
# on some platforms, but it's very fast where it does function.
elsif "foo" != (Inflector.transliterate("föö") rescue nil)
undef_method :transliterate
def transliterate(string)
string.mb_chars.normalize(:kd). # Decompose accented characters
gsub(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics).
end
end
# Create the name of a table like Rails does for models to table names. This method
# uses the +pluralize+ method on the last word in the string.
#
# Examples
# "RawScaledScorer".tableize # => "raw_scaled_scorers"
# "egg_and_ham".tableize # => "egg_and_hams"
# "fancyCategory".tableize # => "fancy_categories"
def tableize(class_name)
pluralize(underscore(class_name))
end
# Create a class name from a plural table name like Rails does for table names to models.
# Note that this returns a string and not a Class. (To convert to an actual class
# follow +classify+ with +constantize+.)
#
# Examples:
# "egg_and_hams".classify # => "EggAndHam"
# "posts".classify # => "Post"
#
# Singular names are not handled correctly:
# "business".classify # => "Busines"
def classify(table_name)
# strip out any leading schema name
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
end
# Creates a foreign key name from a class name.
# +separate_class_name_and_id_with_underscore+ sets whether
# the method should put '_' between the name and 'id'.
#
# Examples:
# "Message".foreign_key # => "message_id"
# "Message".foreign_key(false) # => "messageid"
# "Admin::Post".foreign_key # => "post_id"
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
# Ruby 1.9 introduces an inherit argument for Module#const_get and
# #const_defined? and changes their default behavior.
if Module.method(:const_get).arity == 1
# Tries to find a constant with the name specified in the argument string:
#
# "Module".constantize # => Module
# "Test::Unit".constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter whether
# it starts with "::" or not. No lexical context is taken into account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# "C".constantize # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
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
else
def constantize(camel_cased_word) #:nodoc:
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_get(name, false) || constant.const_missing(name)
end
constant
end
end
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# Examples:
# ordinalize(1) # => "1st"
# ordinalize(2) # => "2nd"
# ordinalize(1002) # => "1002nd"
# ordinalize(1003) # => "1003rd"
def ordinalize(number)
if (11..13).include?(number.to_i % 100)
"#{number}th"
else
case number.to_i % 10
when 1; "#{number}st"
when 2; "#{number}nd"
when 3; "#{number}rd"
else "#{number}th"
end
end
end
end
end
# in case active_support/inflector is required without the rest of active_support
require 'active_support/inflections'
require 'active_support/core_ext/string/inflections'
unless String.included_modules.include?(ActiveSupport::CoreExtensions::String::Inflections)
String.send :include, ActiveSupport::CoreExtensions::String::Inflections
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/callbacks.rb | provider/vendor/rails/activesupport/lib/active_support/callbacks.rb | module ActiveSupport
# Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
# before or after an alteration of the object state.
#
# Mixing in this module allows you to define callbacks in your class.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
# end
#
# class ConfigStorage < Storage
# before_save :saving_message
# def saving_message
# puts "saving..."
# end
#
# after_save do |object|
# puts "saved"
# end
#
# def save
# run_callbacks(:before_save)
# puts "- save"
# run_callbacks(:after_save)
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# saving...
# - save
# saved
#
# Callbacks from parent classes are inherited.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
#
# before_save :prepare
# def prepare
# puts "preparing save"
# end
# end
#
# class ConfigStorage < Storage
# before_save :saving_message
# def saving_message
# puts "saving..."
# end
#
# after_save do |object|
# puts "saved"
# end
#
# def save
# run_callbacks(:before_save)
# puts "- save"
# run_callbacks(:after_save)
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# preparing save
# saving...
# - save
# saved
module Callbacks
class CallbackChain < Array
def self.build(kind, *methods, &block)
methods, options = extract_options(*methods, &block)
methods.map! { |method| Callback.new(kind, method, options) }
new(methods)
end
def run(object, options = {}, &terminator)
enumerator = options[:enumerator] || :each
unless block_given?
send(enumerator) { |callback| callback.call(object) }
else
send(enumerator) do |callback|
result = callback.call(object)
break result if terminator.call(result, object)
end
end
end
# TODO: Decompose into more Array like behavior
def replace_or_append!(chain)
if index = index(chain)
self[index] = chain
else
self << chain
end
self
end
def find(callback, &block)
select { |c| c == callback && (!block_given? || yield(c)) }.first
end
def delete(callback)
super(callback.is_a?(Callback) ? callback : find(callback))
end
private
def self.extract_options(*methods, &block)
methods.flatten!
options = methods.extract_options!
methods << block if block_given?
return methods, options
end
def extract_options(*methods, &block)
self.class.extract_options(*methods, &block)
end
end
class Callback
attr_reader :kind, :method, :identifier, :options
def initialize(kind, method, options = {})
@kind = kind
@method = method
@identifier = options[:identifier]
@options = options
end
def ==(other)
case other
when Callback
(self.identifier && self.identifier == other.identifier) || self.method == other.method
else
(self.identifier && self.identifier == other) || self.method == other
end
end
def eql?(other)
self == other
end
def dup
self.class.new(@kind, @method, @options.dup)
end
def hash
if @identifier
@identifier.hash
else
@method.hash
end
end
def call(*args, &block)
evaluate_method(method, *args, &block) if should_run_callback?(*args)
rescue LocalJumpError
raise ArgumentError,
"Cannot yield from a Proc type filter. The Proc must take two " +
"arguments and execute #call on the second argument."
end
private
def evaluate_method(method, *args, &block)
case method
when Symbol
object = args.shift
object.send(method, *args, &block)
when String
eval(method, args.first.instance_eval { binding })
when Proc, Method
method.call(*args, &block)
else
if method.respond_to?(kind)
method.send(kind, *args, &block)
else
raise ArgumentError,
"Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
"a block to be invoked, or an object responding to the callback method."
end
end
end
def should_run_callback?(*args)
[options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } &&
![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) }
end
end
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def define_callbacks(*callbacks)
callbacks.each do |callback|
class_eval <<-"end_eval"
def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block)
callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block)
@#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
@#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks
end # end
#
def self.#{callback}_callback_chain # def self.before_save_callback_chain
@#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
#
if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain)
CallbackChain.new( # CallbackChain.new(
superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain +
@#{callback}_callbacks # @before_save_callbacks
) # )
else # else
@#{callback}_callbacks # @before_save_callbacks
end # end
end # end
end_eval
end
end
end
# Runs all the callbacks defined for the given options.
#
# If a block is given it will be called after each callback receiving as arguments:
#
# * the result from the callback
# * the object which has the callback
#
# If the result from the block evaluates to false, the callback chain is stopped.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
# end
#
# class ConfigStorage < Storage
# before_save :pass
# before_save :pass
# before_save :stop
# before_save :pass
#
# def pass
# puts "pass"
# end
#
# def stop
# puts "stop"
# return false
# end
#
# def save
# result = run_callbacks(:before_save) { |result, object| result == false }
# puts "- save" if result
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# pass
# pass
# stop
def run_callbacks(kind, options = {}, &block)
self.class.send("#{kind}_callback_chain").run(self, options, &block)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/message_encryptor.rb | provider/vendor/rails/activesupport/lib/active_support/message_encryptor.rb | require 'openssl'
module ActiveSupport
# MessageEncryptor is a simple way to encrypt values which get stored somewhere
# you don't trust.
#
# The cipher text and initialization vector are base64 encoded and returned to you.
#
# This can be used in situations similar to the MessageVerifier, but where you don't
# want users to be able to determine the value of the payload.
class MessageEncryptor
class InvalidMessage < StandardError; end
OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
def initialize(secret, cipher = 'aes-256-cbc')
@secret = secret
@cipher = cipher
end
def encrypt(value)
cipher = new_cipher
# Rely on OpenSSL for the initialization vector
iv = cipher.random_iv
cipher.encrypt
cipher.key = @secret
cipher.iv = iv
encrypted_data = cipher.update(Marshal.dump(value))
encrypted_data << cipher.final
[encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
end
def decrypt(encrypted_message)
cipher = new_cipher
encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
cipher.decrypt
cipher.key = @secret
cipher.iv = iv
decrypted_data = cipher.update(encrypted_data)
decrypted_data << cipher.final
Marshal.load(decrypted_data)
rescue OpenSSLCipherError, TypeError
raise InvalidMessage
end
def encrypt_and_sign(value)
verifier.generate(encrypt(value))
end
def decrypt_and_verify(value)
decrypt(verifier.verify(value))
end
private
def new_cipher
OpenSSL::Cipher::Cipher.new(@cipher)
end
def verifier
MessageVerifier.new(@secret)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/json.rb | provider/vendor/rails/activesupport/lib/active_support/json.rb | require 'active_support/json/decoding'
require 'active_support/json/encoding'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/base64.rb | provider/vendor/rails/activesupport/lib/active_support/base64.rb | begin
require 'base64'
rescue LoadError
end
module ActiveSupport
if defined? ::Base64
Base64 = ::Base64
else
# Base64 provides utility methods for encoding and de-coding binary data
# using a base 64 representation. A base 64 representation of binary data
# consists entirely of printable US-ASCII characters. The Base64 module
# is included in Ruby 1.8, but has been removed in Ruby 1.9.
module Base64
# Encodes a string to its base 64 representation. Each 60 characters of
# output is separated by a newline character.
#
# ActiveSupport::Base64.encode64("Original unencoded string")
# # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==\n"
def self.encode64(data)
[data].pack("m")
end
# Decodes a base 64 encoded string to its original representation.
#
# ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
# # => "Original unencoded string"
def self.decode64(data)
data.unpack("m").first
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/buffered_logger.rb | provider/vendor/rails/activesupport/lib/active_support/buffered_logger.rb | module ActiveSupport
# Inspired by the buffered logger idea by Ezra
class BufferedLogger
module Severity
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
UNKNOWN = 5
end
include Severity
MAX_BUFFER_SIZE = 1000
##
# :singleton-method:
# Set to false to disable the silencer
cattr_accessor :silencer
self.silencer = true
# Silences the logger for the duration of the block.
def silence(temporary_level = ERROR)
if silencer
begin
old_logger_level, self.level = level, temporary_level
yield self
ensure
self.level = old_logger_level
end
else
yield self
end
end
attr_accessor :level
attr_reader :auto_flushing
def initialize(log, level = DEBUG)
@level = level
@buffer = {}
@auto_flushing = 1
@guard = Mutex.new
if log.respond_to?(:write)
@log = log
elsif File.exist?(log)
@log = open(log, (File::WRONLY | File::APPEND))
@log.sync = true
else
FileUtils.mkdir_p(File.dirname(log))
@log = open(log, (File::WRONLY | File::APPEND | File::CREAT))
@log.sync = true
@log.write("# Logfile created on %s" % [Time.now.to_s])
end
end
def add(severity, message = nil, progname = nil, &block)
return if @level > severity
message = (message || (block && block.call) || progname).to_s
# If a newline is necessary then create a new message ending with a newline.
# Ensures that the original message is not mutated.
message = "#{message}\n" unless message[-1] == ?\n
buffer << message
auto_flush
message
end
for severity in Severity.constants
class_eval <<-EOT, __FILE__, __LINE__
def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
end # end
#
def #{severity.downcase}? # def debug?
#{severity} >= @level # DEBUG >= @level
end # end
EOT
end
# Set the auto-flush period. Set to true to flush after every log message,
# to an integer to flush every N messages, or to false, nil, or zero to
# never auto-flush. If you turn auto-flushing off, be sure to regularly
# flush the log yourself -- it will eat up memory until you do.
def auto_flushing=(period)
@auto_flushing =
case period
when true; 1
when false, nil, 0; MAX_BUFFER_SIZE
when Integer; period
else raise ArgumentError, "Unrecognized auto_flushing period: #{period.inspect}"
end
end
def flush
@guard.synchronize do
unless buffer.empty?
old_buffer = buffer
@log.write(old_buffer.join)
end
# Important to do this even if buffer was empty or else @buffer will
# accumulate empty arrays for each request where nothing was logged.
clear_buffer
end
end
def close
flush
@log.close if @log.respond_to?(:close)
@log = nil
end
protected
def auto_flush
flush if buffer.size >= @auto_flushing
end
def buffer
@buffer[Thread.current] ||= []
end
def clear_buffer
@buffer.delete(Thread.current)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/inflections.rb | provider/vendor/rails/activesupport/lib/active_support/inflections.rb | module ActiveSupport
Inflector.inflections do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
inflect.singular(/(^analy)ses$/i, '\1sis')
inflect.singular(/([^f])ves$/i, '\1fe')
inflect.singular(/(hive)s$/i, '\1')
inflect.singular(/(tive)s$/i, '\1')
inflect.singular(/([lr])ves$/i, '\1f')
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
inflect.singular(/(s)eries$/i, '\1eries')
inflect.singular(/(m)ovies$/i, '\1ovie')
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
inflect.singular(/([m|l])ice$/i, '\1ouse')
inflect.singular(/(bus)es$/i, '\1')
inflect.singular(/(o)es$/i, '\1')
inflect.singular(/(shoe)s$/i, '\1')
inflect.singular(/(cris|ax|test)es$/i, '\1is')
inflect.singular(/(octop|vir)i$/i, '\1us')
inflect.singular(/(alias|status)es$/i, '\1')
inflect.singular(/^(ox)en/i, '\1')
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
inflect.singular(/(database)s$/i, '\1')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
inflect.uncountable(%w(equipment information rice money species series fish sheep))
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.