repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
datacite/cheetoh
spec/apis/create_spec.rb
require "rails_helper" describe "create", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5072/0000-03vc" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "missing valid doi parameter" do doi = "20.5072/0000-03vc" put "/id/doi:#{doi}", nil, headers expect(last_response.body).to eq("error: no doi provided") expect(last_response.status).to eq(400) end it "missing login credentials" do put "/id/doi:#{doi}" expect(last_response.headers["WWW-Authenticate"]).to eq("Basic realm=\"ez.stage.datacite.org\"") expect(last_response.body).to eq("HTTP Basic: Access denied.\n") expect(last_response.status).to eq(401) end it "wrong login credentials" do doi = "10.5072/bc11-cqw70" wrong_credentials = { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, "123") } datacite = File.read(file_fixture('10.5072_bc11-cqw7.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl put "/id/doi:#{doi}", params, wrong_credentials expect(last_response.status).to eq(401) expect(last_response.body).to eq("error: unauthorized") end it "no params" do doi = "10.5072/bc11-cqw1" put "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(400) response = last_response.body.from_anvl expect(response["error"]).to eq("no _profile provided") end it "create new doi" do datacite = File.read(file_fixture('10.5072_bc11-cqw7.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl doi = "10.5072/bc11-cqw7" put "/id/doi:#{doi}", params, headers response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/bc11-cqw7") expect(response["datacite"]).to eq(datacite.strip) expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") expect(last_response.status).to eq(200) end it "doi already exists" do datacite = File.read(file_fixture('10.5072_bc11-cqw7.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl doi = "10.5072/bc11-cqw7" put "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(400) response = last_response.body.from_anvl expect(response["error"]).to eq("doi:10.5072/bc11-cqw7 has already been registered") end it "change using schema.org" do schema_org = File.read(file_fixture('schema_org.json')) params = { "schema_org" => schema_org, "_profile" => "schema_org" }.to_anvl doi = "10.5072/bc11-cqw7" post "/id/doi:#{doi}", params, headers response = last_response.body.from_anvl input = JSON.parse(schema_org) output = JSON.parse(response["schema_org"]) expect(response["success"]).to eq("doi:10.5072/bc11-cqw7") expect(response["_status"]).to eq("reserved") expect(output["author"]).to eq("@id"=>"https://orcid.org/0000-0003-1419-2405", "@type"=>"Person", "familyName"=>"Fenner", "givenName"=>"Martin", "name"=>"<NAME>") expect(response["datacite"]).to be_nil expect(last_response.status).to eq(200) end it "change datacite xml" do datacite = File.read(file_fixture('10.5072_bc11-cqw7.xml')) params = { "datacite" => datacite }.to_anvl doi = "10.5072/bc11-cqw7" post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/bc11-cqw7") expect(response["datacite"]).to eq(datacite.strip) expect(response["_status"]).to eq("reserved") end it "delete new doi" do datacite = File.read(file_fixture('10.5072_bc11-cqw7.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" doi = "10.5072/bc11-cqw7" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/bc11-cqw7") expect(response["_target"]).to eq(url) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content.upcase).to eq("10.5072/BC11-CQW7") end end
datacite/cheetoh
spec/apis/heartbeat_spec.rb
<filename>spec/apis/heartbeat_spec.rb require 'rails_helper' describe '/heartbeat', type: :api do it "get heartbeat" do get '/heartbeat' expect(last_response.status).to eq(200) expect(last_response.body).to eq("success: MDS is up") end end
datacite/cheetoh
spec/anvl_spec.rb
<reponame>datacite/cheetoh require 'rails_helper' describe Hash do describe "Anvl" do context "to_anvl" do it "convert" do hsh = { "_status" => "public" } expect(hsh.to_anvl).to eq("_status: public") end it "escape newlines" do hsh = { "name" => "Josiah\nCarberry" } expect(hsh.to_anvl).to eq("name: Josiah%0ACarberry") end end end end describe String do describe "Anvl" do context "from_anvl" do it "convert" do str = "_status: public" expect(str.from_anvl).to eq("_status"=>"public") end it "escaped newlines" do str = "name: Josiah%0ACarberry" expect(str.from_anvl).to eq("name"=>"Josiah\nCarberry") end it "anvl file" do str = File.read(file_fixture('ieee.txt')) expect(str.from_anvl["_target"]).to eq("https://ieee-dataport.org/documents/dataset-nuclei-segmentation-based-tripple-negative-breast-cancer-patients") expect(str.from_anvl["datacite.resourcetype"]).to eq("Dataset") end end end end
datacite/cheetoh
app/controllers/concerns/doiable.rb
<filename>app/controllers/concerns/doiable.rb module Doiable extend ActiveSupport::Concern included do include Bolognese::Utils include Bolognese::DoiUtils UPPER_LIMIT = 1073741823 STATES = { "draft" => "reserved", "registered" => "unavailable", "findable" => "public" } def ez_response(response, options={}) options[:profile] ||= :datacite attributes = response.dig("data", "attributes").to_h status = STATES[attributes["state"]] || "public" status = [status, attributes["reason"]].join(" | ") if status == "unavailable" && attributes["reason"].present? export = (status == "public") ? "yes" : "no" if options[:profile] == :datacite metadata = attributes["xml"].present? ? Base64.decode64(attributes["xml"]) : nil else metadata = get_metadata_by_content_type(doi: attributes["doi"], profile: options[:profile].to_s) end { "success" => "doi:#{attributes["doi"]}", "_target" => attributes["url"], options[:profile] => metadata, "_profile" => options[:profile], "_datacenter" => response.dig("data", "relationships", "client", "data", "id").upcase, "_export" => export, "_created" => Time.parse(attributes["created"]).to_i, "_updated" => Time.parse(attributes["updated"]).to_i, "_status" => status } end def get_metadata_by_content_type(doi: nil, profile: nil) profile ||= "datacite" accept = SUPPORTED_PROFILES[profile.to_sym] url = "#{ENV['API_URL']}/dois/#{doi}" response = Maremma.get(url, accept: accept, username: ENV['MDS_USERNAME'], password: ENV['<PASSWORD>'], raw: true) return nil unless response.status == 200 response.body["data"] end def is_ark?(str) str.to_s.starts_with?("ark:") end def generate_random_doi(str, options={}) prefix = validate_prefix(str) fail IdentifierError, "No valid prefix found" unless prefix.present? shoulder = str.split("/", 2)[1].to_s.downcase encode_doi(prefix, shoulder: shoulder, number: options[:number]) end def encode_doi(prefix, options={}) prefix = validate_prefix(prefix) return nil unless prefix.present? number = options[:number].to_s.scan(/\d+/).join("").to_i number = SecureRandom.random_number(UPPER_LIMIT) unless number > 0 shoulder = options[:shoulder].to_s shoulder += "-" if shoulder.present? length = 8 split = 4 prefix.to_s + "/" + shoulder + Base32::URL.encode(number, split: split, length: length, checksum: true) end def decode_param(str) return nil unless str.present? URI.decode(str) end end module ClassMethods require "uri" def put_doi(doi, options={}) return OpenStruct.new(body: { "errors" => [{ "title" => "Username or password missing" }] }) unless options[:username].present? && options[:password].present? return OpenStruct.new(body: { "errors" => [{ "title" => "Not a valid HTTP(S) or FTP URL" }] }) unless options[:url].blank? || /\A(http|https|ftp):\/\/[\S]+/.match(options[:url]) # update doi status if options[:target_status] == "reserved" || doi.start_with?("10.5072") reason = nil event = nil elsif options[:target_status].to_s.start_with?("unavailable") reason = separate_reason(options[:target_status].to_s) event = "hide" else reason = nil event = "publish" end xml = options[:data].present? ? ::Base64.strict_encode64(options[:data]) : nil creators = options[:creator].present? ? options[:creator].to_s.split(";").map { |a| { "name" => a.strip }} : nil titles = options[:title].present? ? [{ "title"=> options[:title] }] : nil types = options[:resource_type_general].present? ? { "resourceTypeGeneral" => options[:resource_type_general], "resourceType" => options[:resource_type].presence }.compact : nil # https://github.com/datacite/lupo/blob/62b8ae4069be3418f8312265f015db5827eed2e8/app/controllers/dois_controller.rb#L414-L464 attributes = { "url" => options[:url], "xml" => xml, "creators" => creators, "titles" => titles, "publisher" => options[:publisher], "publicationYear" => options[:publication_year], "types" => types, "source" => "ez", "event" => event, "reason" => reason }.compact data = { "data" => { "type" => "dois", "attributes" => attributes, "relationships"=> { "client"=> { "data"=> { "type"=> "clients", "id"=> options[:username] } } } } } url = "#{ENV['API_URL']}/dois/#{doi}" Maremma.put(url, content_type: 'application/vnd.api+json', data: data.to_json, username: options[:username], password: options[:password]) end def separate_reason string if string.include?("%7C") string.split("%7C", -1).map(&:strip).last elsif string.include?("|") string.split("|", -1).map(&:strip).last else "" end end def post_doi(doi, options={}) return OpenStruct.new(body: { "errors" => [{ "title" => "Username or password missing" }] }) unless options[:username].present? && options[:password].present? return OpenStruct.new(body: { "errors" => [{ "title" => "Not a valid HTTP(S) or FTP URL" }] }) unless options[:url].blank? || /\A(http|https|ftp):\/\/[\S]+/.match(options[:url]) # update doi status if options[:target_status] == "reserved" || doi.start_with?("10.5072") then reason = nil event = nil elsif options[:target_status].to_s.start_with?("unavailable") reason = separate_reason(options[:target_status].to_s) event = "hide" else reason = nil event = "publish" end xml = options[:data].present? ? ::Base64.strict_encode64(options[:data]) : nil creators = options[:creator].present? ? options[:creator].to_s.split(";").map { |a| { "name" => a.strip }} : nil titles = options[:title].present? ? [{ "title"=> options[:title] }] : nil types = options[:resource_type_general].present? ? { "resourceTypeGeneral" => options[:resource_type_general], "resourceType" => options[:resource_type].presence }.compact : nil attributes = { "doi" => doi, "url" => options[:url], "xml" => xml, "creators" => creators, "titles" => titles, "types" => types, "publisher" => options[:publisher], "publicationYear" => options[:publication_year], "source" => "ez", "event" => event, "reason" => reason }.compact data = { "data" => { "type" => "dois", "attributes" => attributes, "relationships"=> { "client"=> { "data"=> { "type"=> "clients", "id"=> options[:username] } } } } } url = "#{ENV['API_URL']}/dois" Maremma.post(url, content_type: 'application/vnd.api+json', data: data.to_json, username: options[:username], password: options[:password]) end def get_doi(doi, options={}) url = "#{ENV['API_URL']}/dois/#{doi}" Maremma.get(url, content_type: 'application/vnd.api+json', username: ENV['ADMIN_USERNAME'], password: ENV['<PASSWORD>']) end def delete_doi(doi, options={}) return OpenStruct.new(body: { "errors" => [{ "title" => "Username or password missing" }] }) unless options[:username].present? && options[:password].present? url = "#{ENV['API_URL']}/dois/#{doi}" Maremma.delete(url, username: options[:username], password: options[:password]) end def get_dois(options={}) return OpenStruct.new(body: { "errors" => [{ "title" => "Username or password missing" }] }) unless options[:username].present? && options[:password].present? url = "#{ENV['API_URL']}/dois/get-dois" Maremma.get(url, username: options[:username], password: options[:password]) end end end
datacite/cheetoh
spec/apis/random_spec.rb
require "rails_helper" describe "random", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5072/0000-03vc" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "create new doi" do datacite = File.read(file_fixture('10.5072_tba.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl prefix = "10.5072" body = <<~HEREDOC {"data":{"id":"10.5072/bc11-cqw1","type":"dois","attributes":{"doi":"10.5072/bc11-cqw1","identifier":"https://handle.stage.datacite.org/10.5072/bc11-cqw1","url":"https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/","author":{"type":"Person","id":"https://orcid.org/0000-0003-1419-2405", "name":"<NAME>", "given-name":"Martin","family-name":"Fenner"},"title":"Differences between ORCID and DataCite Metadata","container-title":"DataCite Blog", "description":{"type":"Abstract","text":"One of the first tasks for DataCite in the European Commission-funded THOR project, which started in June, was to contribute to a comparison of the ORCID and DataCite metadata standards. Together with ORCID, CERN, the British Library and Dryad we looked..."}, "resource-type-subtype":"BlogPosting","license":"https://creativecommons.org/licenses/by/4.0","version":1,"related-identifier":[{"type":"CreativeWork","id":"https://doi.org/10.5281/zenodo.30799","relation-type":"References"}],"schema-version":"http://datacite.org/schema/kernel-4","state":"draft", "published":"2015-09-18","registered":null,"updated":"2018-01-18T22:21:27.000Z"},"relationships":{"client":{"meta":{}},"provider":{"meta":{}},"resource-type":{"meta":{}},"media":{"meta":{}}}}} HEREDOC # stub API responses, as the DOI changes with every request stub_request(:get, /api.stage.datacite.org/) .to_return(status: 404, body: '{"errors":[{"status":"404","title":"The resource you are looking for doesn''t exist."}]}') stub_request(:post, /mds.stage.datacite.org\/metadata/) .to_return(status: 201, body: 'OK (10.5072/BC11-CQW1)') stub_request(:put, /mds.stage.datacite.org\/doi/) .to_return(status: 201, body: 'OK') stub_request(:patch, /api.stage.datacite.org/) .to_return(status: 200, headers: { "Content-Type" => "application/vnd.api+json; charset=utf-8" }, body: body) post "/shoulder/doi:#{prefix}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to start_with("doi:#{prefix}") expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") end end
datacite/cheetoh
spec/apis/mint_spec.rb
<filename>spec/apis/mint_spec.rb require "rails_helper" describe "mint", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5072/0000-03vc" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "missing valid prefix parameter" do datacite = File.read(file_fixture('10.5072_3mfp-6m52.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl doi = "20.5072/abc" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(400) expect(last_response.body).to eq("error: No valid prefix found") end it "missing login credentials" do post "/shoulder/doi:#{doi}" expect(last_response.status).to eq(401) expect(last_response.headers["WWW-Authenticate"]).to eq("Basic realm=\"ez.stage.datacite.org\"") expect(last_response.body).to eq("HTTP Basic: Access denied.\n") end it "wrong login credentials" do wrong_credentials = { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, "123") } datacite = File.read(file_fixture('10.5072_tba.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url, "_number" => "122149076" }.to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, wrong_credentials expect(last_response.status).to eq(401) expect(last_response.body).to eq("error: unauthorized") end it "no params" do doi = "10.5072" post "/shoulder/doi:#{doi}", nil, headers expect(last_response.status).to eq(400) response = last_response.body.from_anvl expect(response["error"]).to eq("no _profile provided") end # we seed with _number to avoid random numbers in tests it "create new doi" do datacite = File.read(file_fixture('10.5072_tba.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url, "_number" => "122149076" }.to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/3MFP-6M52") end it "nothing to update" do doi = "10.5072/3mfp-6m52" post "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(400) response = last_response.body.from_anvl expect(response["error"]).to eq("No _profile, _target or _status provided") end it "change redirect url and datacite xml" do datacite = File.read(file_fixture('10.5072_3mfp-6m52.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url }.to_anvl doi = "10.5072/3mfp-6m52" post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["datacite"]).to eq(datacite.strip) expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") end it "change redirect url" do url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "_target" => url }.to_anvl doi = "10.5072/3mfp-6m52" post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") end it "change datacite xml" do datacite = File.read(file_fixture('10.5072_3mfp-6m52.xml')) params = { "datacite" => datacite }.to_anvl doi = "10.5072/3mfp-6m52" post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["datacite"]).to eq(datacite.strip) expect(response["_status"]).to eq("reserved") end # it "status unavailable" do # datacite = File.read(file_fixture('10.5072_bc11-cqw1.xml')) # params = { "_status" => "unavailable" }.to_anvl # doi = "10.5072/bc11-cqw1" # post "/id/doi:#{doi}", params, headers # expect(last_response.status).to eq(200) # response = last_response.body.from_anvl # expect(response["success"]).to eq("doi:10.5072/bc11-cqw1") # expect(response["datacite"]).to eq(datacite.strip) # expect(response["_status"]).to eq("unavailable") # end # it "status reserved" do # datacite = File.read(file_fixture('10.5072_3mfp-6m52.xml')) # params = { "_status" => "public" }.to_anvl # doi = "10.5072/3mfp-6m52" # post "/id/doi:#{doi}", params, headers # expect(last_response.status).to eq(200) # response = last_response.body.from_anvl # expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") # expect(response["datacite"]).to eq(datacite.strip) # expect(response["_status"]).to eq("reserved") # end it "delete new doi" do datacite = File.read(file_fixture('10.5072_tba.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" doi = "10.5072/3mfp-6m52" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["_target"]).to eq(url) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/3MFP-6M52") end it "create new reserved doi" do params = { "_status" => "reserved", "_number" => "122149076" }.to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mfp-6m52") expect(response["_status"]).to eq("reserved") end it "delete reserved doi" do doi = "10.5072/3mfp-6m52" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body hsh = response.from_anvl expect(hsh["success"]).to eq("doi:10.5072/3mfp-6m52") end end
datacite/cheetoh
config/application.rb
<reponame>datacite/cheetoh<filename>config/application.rb require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" # require "active_record/railtie" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_view/railtie" # require "action_cable/engine" # require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) # load ENV variables from .env file if it exists env_file = File.expand_path("../../.env", __FILE__) if File.exist?(env_file) require 'dotenv' Dotenv.load! env_file end # load ENV variables from container environment if json file exists # see https://github.com/phusion/baseimage-docker#envvar_dumps env_json_file = "/etc/container_environment.json" if File.exist?(env_json_file) env_vars = JSON.parse(File.read(env_json_file)) env_vars.each { |k, v| ENV[k] = v } end # default values for some ENV variables ENV['APPLICATION'] ||= "cheetoh" ENV['HOSTNAME'] ||= "cheetoh.local" ENV['API_URL'] ||= "https://api.stage.datacite.org" ENV['REALM'] ||= "ez.stage.datacite.org" ENV['MEMCACHE_SERVERS'] ||= "memcached:11211" ENV['SITE_TITLE'] ||= "EZ API" ENV['LOG_LEVEL'] ||= "info" ENV['GITHUB_URL'] ||= "https://github.com/datacite/cheetoh" ENV['TRUSTED_IP'] ||= "127.0.0.0/8" module Cheetoh class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. config.autoload_paths << Rails.root.join('lib') # Only loads a smaller set of middleware suitable for API only apps. # Middleware like session, flash, cookies can be added back manually. # Skip views, helpers and assets when generating a new resource. config.api_only = true # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. # Previous versions had false. config.active_support.to_time_preserves_timezone = true # Configure SSL options to enable HSTS with subdomains. Previous versions had false. config.ssl_options = { hsts: { subdomains: true } } # secret_key_base is not used by Rails API, as there are no sessions config.secret_key_base = 'blipblapblup' # Use memcached as cache store config.cache_store = :dalli_store, nil, { expires_in: 7.days } # make sure all input is UTF-8 config.middleware.insert 0, Rack::UTF8Sanitizer, additional_content_types: ['application/vnd.api+json', 'application/xml'] # correctly parse request bodies encoded using ANVL, needs to handle UTF-8 sanitization config.middleware.insert_after Rack::UTF8Sanitizer, Rack::Parser, :parsers => { 'application/x-www-form-urlencoded' => proc { |body| body.gsub(/%20/, " ").gsub(/%22/, "\"").gsub(/%3C/, "<").gsub(/%3E/, ">").gsub(/%7B/, "{").gsub(/%7D/, "}").gsub(/%0A(_profile|_status|_target|_number|_export|datacite|schema_org|ris|bibtex)/, "\n\\1").from_anvl }, 'text/plain' => proc { |body| body.gsub(/%20/, " ").gsub(/%22/, "\"").gsub(/%3C/, "<").gsub(/%3E/, ">").gsub(/%7B/, "{").gsub(/%7D/, "}").gsub(/%0A(_profile|_status|_target|_number|_export|datacite|schema_org|ris|bibtex)/, "\n\\1").from_anvl } } # compress responses with deflate or gzip config.middleware.use Rack::Deflater end end
datacite/cheetoh
app/controllers/application_controller.rb
class ApplicationController < ActionController::API include ActionController::HttpAuthentication::Basic::ControllerMethods include Bolognese::DoiUtils include Bolognese::Utils attr_accessor :username, :password before_action :set_raven_context after_action :set_consumer_header # check that username and password exist # store them in instance variables used for calling MDS API def authenticate_user_with_basic_auth! @username, @password = ActionController::HttpAuthentication::Basic::user_name_and_password(request) request_http_basic_authentication(realm = ENV['REALM']) unless @username.present? && @password.present? end def set_consumer_header if username response.headers['X-Credential-Username'] = username else response.headers['X-Anonymous-Consumer'] = true end end def route_not_found render plain: "error:resource not found", status: :not_found end unless Rails.env.development? rescue_from *(RESCUABLE_EXCEPTIONS) do |exception| status = case exception.class.to_s when "CanCan::AccessDenied", "JWT::DecodeError" then 401 when "AbstractController::ActionNotFound", "ActionController::RoutingError" then 404 when "ActiveModel::ForbiddenAttributesError", "ActionController::UnpermittedParameters", "NoMethodError" then 422 when "NotImplementedError" then 501 else 400 end # EZID functionality not supported by this service status = 501 if exception.message.end_with?("not supported by this service") if status == 404 message = "bad request - no such identifier" status = 400 elsif status == 401 message = "unauthorized" elsif status == 501 || exception.class.to_s == "IdentifierError" # don't raise Sentry error message = exception.message else Raven.capture_exception(exception) message = exception.message end logger.error "[#{status}]: " + message render plain: "error: " + message, status: status end end def append_info_to_payload(payload) super payload[:uid] = username.downcase if username.present? payload[:data] = request.raw_post.from_anvl if request.raw_post.present? end def set_raven_context if username.present? Raven.user_context( id: username.downcase, ip_address: request.ip ) else Raven.user_context( ip_address: request.ip ) end end end
datacite/cheetoh
spec/apis/invalid_spec.rb
require "rails_helper" describe "invalid", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5438/bc11-cqw10" } let(:url) { "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['<PASSWORD>'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "create new reserved doi" do datacite = File.read(file_fixture('missing_creator.xml')) params = { "datacite" => datacite, "_target" => url, "_status" => "reserved" }.to_anvl put "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5438/bc11-cqw10") expect(response["_profile"]).to eq("datacite") expect(response["_status"]).to eq("reserved") expect(response["_target"]).to eq(url) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5438/BC11-CQW10") end it "show reserved doi" do get "/id/doi:#{doi}" expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5438/bc11-cqw10") expect(response["_profile"]).to eq("datacite") expect(response["_status"]).to eq("reserved") expect(response["_target"]).to eq(url) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5438/BC11-CQW10") end # it "status public" do # params = { "_status" => "public" }.to_anvl # post "/id/doi:#{doi}", params, headers # expect(last_response.status).to eq(200) # response = last_response.body.from_anvl # expect(response["success"]).to eq("doi:10.5438/bc11-cqw10") # expect(response["_profile"]).to eq("datacite") # #expect(response["_target"]).to eq(url) # expect(response["_status"]).to eq("reserved") # # doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) # expect(doc.at_css("identifier").content).to eq("10.5438/BC11-CQW10") # end it "delete doi and metadata" do delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5438/bc11-cqw10") expect(response["_target"]).to eq(url) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5438/BC11-CQW10") end end
datacite/cheetoh
config/initializers/constants.rb
class IdentifierError < RuntimeError; end RESCUABLE_EXCEPTIONS = [CanCan::AccessDenied, JWT::DecodeError, JWT::VerificationError, IdentifierError, NotImplementedError, AbstractController::ActionNotFound, ActionController::RoutingError, ActionController::ParameterMissing, ActionController::UnpermittedParameters, NoMethodError] SUPPORTED_PROFILES = { datacite: "application/vnd.datacite.datacite+xml", bibtex: "application/x-bibtex", ris: "application/x-research-info-systems", schema_org: "application/vnd.schemaorg.ld+json", citeproc: "application/vnd.citationstyles.csl+json" }
datacite/cheetoh
spec/apis/update_spec.rb
require "rails_helper" describe "update", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5072/0000-03vc" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end context "missing" do it "missing valid doi parameter" do doi = "20.5072/0000-03vc" post "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(400) expect(last_response.body).to eq("error: bad request - no such identifier") end it "missing login credentials" do post "/id/doi:#{doi}" expect(last_response.status).to eq(401) expect(last_response.headers["WWW-Authenticate"]).to eq("Basic realm=\"ez.stage.datacite.org\"") expect(last_response.body).to eq("HTTP Basic: Access denied.\n") end end end
datacite/cheetoh
spec/apis/not_supported_spec.rb
<gh_stars>0 require "rails_helper" describe "login", :type => :api do let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['<PASSWORD>'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "not supported" do get "/login", nil, headers expect(last_response.status).to eq(501) expect(last_response.body).to eq("error: one-time login and session cookies not supported by this service") end end
datacite/cheetoh
spec/apis/user_examples_spec.rb
<reponame>datacite/cheetoh<gh_stars>0 require "rails_helper" describe "user examples", :type => :api, vcr: true, :order => :defined do let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end # context "sbd" do # let(:doi) { "10.5072/fk2/sbdtest/501" } # it "create doi" do # str = File.read(file_fixture('10.5072_fk2_sbdtest_501.txt')).from_anvl # params = { "datacite" => str[:datacite], "_target" => str[:_target], "_status" => "reserved" }.to_anvl # doi = "10.5072/fk2/sbdtest/501" # put "/id/doi:#{doi}", params, headers # expect(last_response.status).to eq(200) # response = last_response.body.from_anvl # expect(response["success"]).to eq("doi:10.5072/fk2/sbdtest/501") # expect(response["_target"]).to eq(str[:_target]) # expect(response["_status"]).to eq("reserved") # doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) # expect(doc.at_css("identifier").content).to eq("10.5072/FK2/SBDTEST/501") # end # it "delete doi" do # doi = "10.5072/fk2/sbdtest/501" # delete "/id/doi:#{doi}", nil, headers # expect(last_response.body).to eq(200) # response = last_response.body.from_anvl # expect(response["success"]).to eq("doi:10.5072/fk2/sbdtest/501") # expect(response["_target"]).to eq("http://data.sbgrid.org/dataset/501") # doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) # expect(doc.at_css("identifier").content).to eq("10.5072/FK2/SBDTEST/501") # end # end context "uva" do it "mint doi" do str = File.read(file_fixture('10.5072_fk2_test.txt')).from_anvl params = { "datacite" => str[:datacite], "_target" => str[:_target], "_status" => "reserved", "_number" => "1225646076" }.to_anvl doi = "10.5072/fk2" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/fk2-1-4gvq-zw33") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/FK2-1-4GVQ-ZW33") end it "delete doi" do doi = "10.5072/fk2-1-4gvq-zw33" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/fk2-1-4gvq-zw33") expect(response["_target"]).to eq("http://google.com") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/FK2-1-4GVQ-ZW33") end end context "dryad" do it "create doi" do str = File.read(file_fixture('10.5072_DRYAD.B3B0T7S_1.txt')).from_anvl params = { "datacite" => str[:datacite], "_target" => str[:_target], "_status" => "reserved" }.to_anvl doi = "10.5072/DRYAD.B3B0T7S/1" put "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/dryad.b3b0t7s/1") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/DRYAD.B3B0T7S/1") end it "delete doi" do doi = "10.5072/DRYAD.B3B0T7S/1" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/dryad.b3b0t7s/1") expect(response["_target"]).to eq("http://ryan-vm.datadryad.org/resource/doi:10.5072/dryad.b3b0t7s/1") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/DRYAD.B3B0T7S/1") end end context "ieee" do let(:doi) { "10.5072/3mg5-tm67" } it "mint doi" do str = File.read(file_fixture('ieee.txt')).from_anvl params = str.merge("_number" => "122165076").to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/3MG5-TM67") end it "delete minted doi" do delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq("https://ieee-dataport.org/documents/dataset-nuclei-segmentation-based-tripple-negative-breast-cancer-patients") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq(doi.upcase) end it "create doi" do str = File.read(file_fixture('ieee.txt')).from_anvl params = str.merge("_number" => "122165076").to_anvl put "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/3MG5-TM67") end it "delete created doi" do delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq("https://ieee-dataport.org/documents/dataset-nuclei-segmentation-based-tripple-negative-breast-cancer-patients") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq(doi.upcase) end it "mint doi no status" do str = File.read(file_fixture('ieee_no_status.txt')).from_anvl params = str.merge("_number" => "122165076").to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/3MG5-TM67") end it "delete doi no status" do delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/3mg5-tm67") expect(response["_target"]).to eq("https://ieee-dataport.org/documents/dataset-nuclei-segmentation-based-tripple-negative-breast-cancer-patients") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq(doi.upcase) end end context "nd" do let(:doi) { "10.5438/fk2-3mg5-tm67" } it "mint doi" do str = File.read(file_fixture('nd.txt')).from_anvl params = str.merge("_number" => "122165076").to_anvl doi = "10.5438/FK2" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(422) response = last_response.body.from_anvl expect(response["error"]).to eq("[facet 'enumeration'] the value 'invalidresourcetype' is not an element of the set {'audiovisual', 'collection', 'datapaper', 'dataset', 'event', 'image', 'interactiveresource', 'model', 'physicalobject', 'service', 'software', 'sound', 'text', 'workflow', 'other'}. at line 4, column 0") end # it "mint doi newlines" do # str = File.read(file_fixture('nd_newlines.txt')) # params = str + "\n_number: 122165076" # doi = "10.23725/FK2" # post "/shoulder/doi:#{doi}", params, headers # expect(last_response.status).to eq(422) # response = last_response.body.from_anvl # expect(response["error"]).to eq("Missing child element(s). expected is ( {http://datacite.org/schema/kernel-4}creator ). at line 4, column 0") # end end context "tamucc" do let(:doi) { "10.5072/4h3j-wr25" } it "mint doi" do str = File.read(file_fixture('tamucc.txt')).from_anvl params = str.merge("_number" => "152161176").to_anvl doi = "10.5072" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/4h3j-wr25") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/4H3J-WR25") expect(doc.at_css("title").content).to eq("Aqueous geochemistry of Louisiana marshes, May 2015 – October 2016") end it "update doi" do str = File.read(file_fixture('tamucc-update.txt')).from_anvl params = str.to_anvl post "/id/doi:#{doi}", params, headers response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/4h3j-wr25") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("reserved") expect(last_response.status).to eq(200) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/4H3J-WR25") expect(doc.at_css("title").content).to eq("RCYC Focus Groups") end it "delete doi" do doi = "10.5072/4h3j-wr25" delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5072/4h3j-wr25") expect(response["_target"]).to eq("https://data.gulfresearchinitiative.org/data/R6.x805.000:0056") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5072/4H3J-WR25") end end context "ual" do let(:doi) { "10.14454/fk2-4h3j-wr25" } it "mint doi" do str = File.read(file_fixture('ual-register.txt')).from_anvl params = str.merge("_number" => "152161176").to_anvl doi = "10.14454/FK2" post "/shoulder/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.14454/fk2-4h3j-wr25") expect(response["_target"]).to eq("http://localhost/items/2d880b8c-e3b7-4d99-a0ce-c56361dfc126") expect(response["_status"]).to eq("public") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.14454/FK2-4H3J-WR25") end it "update title change" do str = File.read(file_fixture('ual-update.txt')).from_anvl params = str.to_anvl post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.14454/fk2-4h3j-wr25") doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.14454/FK2-4H3J-WR25") expect(doc.at_css("title").content).to eq("Different Title") end it "update for removal" do str = File.read(file_fixture('ual-remove.txt')).from_anvl params = str.to_anvl post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.14454/fk2-4h3j-wr25") expect(response["_status"]).to eq("unavailable | withdrawn") expect(response["_export"]).to eq("no") end it "update for making public" do str = File.read(file_fixture('ual-public.txt')).from_anvl params = str.to_anvl post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.14454/fk2-4h3j-wr25") expect(response["_status"]).to eq("public") expect(response["_export"]).to eq("yes") end it "update for being made private" do str = File.read(file_fixture('ual-private.txt')).from_anvl params = str.to_anvl post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(200) response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.14454/fk2-4h3j-wr25") expect(response["_target"]).to eq(str[:_target]) expect(response["_status"]).to eq("unavailable | not publicly released") expect(response["_export"]).to eq("no") end end end
datacite/cheetoh
spec/apis/regular_prefix_spec.rb
<gh_stars>0 require "rails_helper" describe "regular prefix", :type => :api, vcr: true, :order => :defined do let(:doi) { "10.5438/bc11-cqw8" } let(:username) { ENV['MDS_USERNAME'] } let(:password) { ENV['MDS_PASSWORD'] } let(:headers) do { "HTTP_CONTENT_TYPE" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(username, password) } end it "create new reserved doi normal prefix" do datacite = File.read(file_fixture('10.5072_bc11-cqw8.xml')) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "datacite" => datacite, "_target" => url, "_status" => "reserved" }.to_anvl put "/id/doi:#{doi}", params, headers response = last_response.body.from_anvl expect(response["success"]).to eq("doi:10.5438/bc11-cqw8") expect(response["_target"]).to eq(url) expect(response["_status"]).to eq("reserved") expect(last_response.status).to eq(200) doc = Nokogiri::XML(response["datacite"], nil, 'UTF-8', &:noblanks) expect(doc.at_css("identifier").content).to eq("10.5438/BC11-CQW8") end it "wrong login credentials delete" do headers = ({ "HTTP_ACCEPT" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("name", "password") }) delete "/id/doi:#{doi}", nil, headers expect(last_response.status).to eq(400) expect(last_response.body).to eq("error: doi:#{doi} is not a reserved DOI") end it "wrong login credentials post" do headers = ({ "HTTP_ACCEPT" => "text/plain", "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("name", "password") }) url = "https://blog.datacite.org/differences-between-orcid-and-datacite-metadata/" params = { "_target" => url }.to_anvl post "/id/doi:#{doi}", params, headers expect(last_response.status).to eq(401) expect(last_response.body).to eq("error: unauthorized") end end
leskiger/constant-contact-ruby
lib/constant_contact_ruby/contacts.rb
<gh_stars>1-10 module ConstantContact class Contacts def initialize(session) @session = session end def all @session.get("contacts") end def find end end end
leskiger/constant-contact-ruby
test/session_test.rb
<reponame>leskiger/constant-contact-ruby require 'test_helper' class TestSession < Test::Unit::TestCase context 'Authentication' do setup do @unauthorized_response_mock = mock('Net::HTTPResponse') @unauthorized_response_mock.stubs( :code => '401', :message => "Not Authorized", :content_type => "text/html", :body => '', :header => { 'www-authenticate' => 'Digest realm="api.constantcontact.com", nonce="ab99e2eb0969a35edaa60ccde8c0f8cc", qop="auth"' }) @http_mock = mock('Net::HTTP') Net::HTTP.stubs(:new).returns(@http_mock) @session = ConstantContact::Session.new("user", "pass", "key") end should "authenticate with digest authentication when challenged" do @http_mock.expects(:request).returns(@unauthorized_response_mock) @http_mock.expects(:request).with( @session.get("/ws/customers/user/") end end end
leskiger/constant-contact-ruby
lib/constant_contact_ruby/connection.rb
require 'net/http' require 'digest/md5' module ConstantContact class Connection DOMAIN = "api.constantcontact.com".freeze def initialize(username, password, key) @username = username @password = password @api_key = key @http_login = "#{key}%#{username}" @client = Net::HTTP.new(DOMAIN) @base_url = "/ws/customers/#{@username}" @authentication_params = {} @nonce_count = 0 @cookies = {} end # Send a get request to the specified path. def get(path) req = Net::HTTP::Get.new(@base_url + path) response = handle_request(req) response.each {|k,v| puts "#{k}: #{v}"} response end private # Send the request to the server. If the response is unauthorized, an attempt to log in using http digest # authentication is made. # def handle_request(request) add_cookies!(request) authenticate_request!(request) response = @client.request(request) set_cookies(response) case response when Net::HTTPUnauthorized response = respond_to_challenge(request, response) end end # Adds authentication information to the request based on the challenge from the response. # def respond_to_challenge(request, response) authenticate_header = response['www-authenticate'].downcase authenticate_header.sub!(/^digest /, '') @authentication_params = authenticate_header.split(", ").inject({}) { |h, field| key, value = field.split("=") h[key] = value.gsub(/^"|"$/, '') # strip quotes. h } add_cookies!(request) authenticate_request!(request) request.each{|k,v| puts "#{k}: #{v}" } # Resend the request @client.request(request) end # Does the legwork for HTTP Digest authentication (See http://www.ietf.org/rfc/rfc2617.txt). # def authenticate_request!(request) return if @authentication_params.empty? puts "AUTHENTICATION PARAMS: #{@authentication_params.inspect}" @nonce_count += 1 cnonce = Digest::MD5.hexdigest(Time.now.to_s + rand(65535).to_s) a1 = "#{@http_login}:#{@authentication_params['realm']}:#{@password}" a2 = "#{request.method}:#{request.path}" response_digest = Digest::MD5.hexdigest(a1) << ':' << @authentication_params['nonce'] << ':' << ('%08x' % @nonce_count) << ':' << cnonce << ':' << @authentication_params['qop'] << ':' << Digest::MD5.hexdigest(a2) request['Authorization'] = "Digest username=\"#{@http_login}\", " << "realm=\"#{@authentication_params['realm']}\", " << "nonce=\"#{@authentication_params['nonce']}\", " << "uri=\"#{request.path}\", " << "nc=#{'%08x' % @nonce_count}, " << "qop=\"#{@authentication_params['qop']}\", " << "cnonce=\"#{cnonce}\", " << "response=\"#{Digest::MD5.hexdigest(response_digest)}\"" end # Adds the cookie header. ConstantContact uses some sort of load balancer and requires cookies to keep track of # session state. Without rudimentary cookie support, interfacing with the API is impossible. # def add_cookies!(request) request['Cookie'] = @cookies.collect{|k, v| "#{k}=#{v}"}.join(", ") end # Stores cookies in the response for later use # def set_cookies(response) cookie_str = response.header['set-cookie'] return if cookie_str.nil? fields = cookie_str.split("; ").inject({}) { |h, field| key, value = field.split("=") h[key] = value h } # This is obviously not a generalized cookie implementation. Heh. fields.delete('path') @cookies = fields end end end
no-reply/Bplgeo
lib/bplgeo/parser.rb
module Bplgeo class Parser def self.bplgeo_config root = Rails.root || './test/dummy' env = Rails.env || 'test' @bplgeo_config ||= YAML::load(ERB.new(IO.read(File.join(root, 'config', 'bplgeo.yml'))).result)[env].with_indifferent_access end def self.mapquest_key bplgeo_config[:mapquest_key] || '<mapquest_key>' end def self.bing_key bplgeo_config[:bing_key] || '<bing_key>' end def self.timeout bplgeo_config[:timeout] end #Note: Limited to only looking at United States places... def self.parse_bing_api(term, parse_term_flag=false) return_hash = {} retry_count = 3 #Skip if no bing_key... possibly move this elsewhere? return return_hash if self.bing_key == '<bing_key>' return_hash[:original_term] = term term = Bplgeo::Standardizer.parse_for_geographic_term(term) if parse_term_flag term = Bplgeo::Standardizer.standardize_geographic_term(term) if term.blank? return {} end return_hash[:standardized_term] = term #Bing API does badly with parentheses... if term.match(/[\(\)]+/) return {} end #Sometimes with building, city, state, bing is dumb and will only return state. Example: Boston Harbor, Boston, Mass. #So if not a street address, pass to have google handle it for better results... #Example of another bad record: South Street bridge, West Bridgewater, Mass. would give a place in Holyoke if term.split(',').length >= 3 && term.match(/\d/).blank? && term.downcase.match(/ave\.*,/).blank? && term.downcase.match(/avenue\.*,/).blank? && term.downcase.match(/street\.*,/).blank? && term.downcase.match(/st\.*,/).blank? && term.downcase.match(/road\.*,/).blank? && term.downcase.match(/rd\.*,/).blank? return {} end Geocoder.configure(:lookup => :bing,:api_key => self.bing_key,:timeout => self.timeout, :always_raise => :all) bing_api_result = Geocoder.search(term) rescue SocketError => e retry unless (retry_count -= 1).zero? else #Use only for United States results... international results are inaccurate. if bing_api_result.present? && bing_api_result.first.data["address"]["countryRegion"] == 'United States' if bing_api_result.first.data["entityType"] == 'Neighborhood' return {} #Doesn't return a city... Google handles this better. end if bing_api_result.first.data["address"]["addressLine"].present? return_hash[:term_differs_from_tgn] = true return_hash[:street_part] = bing_api_result.first.data["address"]["addressLine"] return_hash[:coords] = {:latitude=>bing_api_result.first.data["geocodePoints"].first["coordinates"].first.to_s, :longitude=>bing_api_result.first.data["geocodePoints"].first["coordinates"].last.to_s, :combined=>bing_api_result.first.data["geocodePoints"].first["coordinates"].first.to_s + ',' + bing_api_result.first.data["geocodePoints"].first["coordinates"].last.to_s} end return_hash[:country_part] = bing_api_result.first.data["address"]["countryRegion"] if return_hash[:country_part] == 'United States' return_hash[:state_part] = Bplgeo::Constants::STATE_ABBR[bing_api_result.first.data["address"]["adminDistrict"]] else return_hash[:state_part] = bing_api_result.first.data["address"]["adminDistrict"] end return_hash[:city_part] = bing_api_result.first.data["address"]["locality"] else return {} end #Only return if USA for now. International results often awful. return return_hash[:country_part] == 'United States' ? return_hash : {} end #Mapquest allows unlimited requests - start here? def self.parse_mapquest_api(term, parse_term_flag=false) return_hash = {} retry_count = 3 #Skip if no bing_key... possibly move this elsewhere? return return_hash if self.mapquest_key == '<mapquest_key>' return_hash[:original_term] = term term = Bplgeo::Standardizer.parse_for_geographic_term(term) if parse_term_flag term = Bplgeo::Standardizer.standardize_geographic_term(term) if term.blank? return {} end return_hash[:standardized_term] = term #Mapquest returns bad data for: Manchester, Mass. if term.include?('Manchester') || term.include?('Atlanta, MI') return {} end #Messed up with just neighborhoods. Example: Hyde Park (Boston, Mass.) or Hyde Park (Boston, Mass.) #So if not a street address, pass to have google handle it for better results... if term.split(',').length >= 3 && term.match(/\d/).blank? && term.downcase.match(/ave\.*,/).blank? && term.downcase.match(/avenue\.*,/).blank? && term.downcase.match(/street\.*,/).blank? && term.downcase.match(/st\.*,/).blank? && term.downcase.match(/road\.*,/).blank? && term.downcase.match(/rd\.*,/).blank? return {} end Geocoder.configure(:lookup => :mapquest,:api_key => self.mapquest_key,:timeout => self.timeout, :always_raise => :all) mapquest_api_result = Geocoder.search(term) rescue SocketError => e retry unless (retry_count -= 1).zero? else #If this call returned a result... if mapquest_api_result.present? if mapquest_api_result.first.data["street"].present? #return_hash[:term_differs_from_tgn] = true return_hash[:street_part] = mapquest_api_result.first.data["street"] return_hash[:coords] = {:latitude=>mapquest_api_result.first.data['latLng']['lat'].to_s, :longitude=>mapquest_api_result.first.data['latLng']['lng'].to_s, :combined=>mapquest_api_result.first.data['latLng']['lat'].to_s + ',' + mapquest_api_result.first.data['latLng']['lng'].to_s} end return_hash[:country_part] = Country.new(mapquest_api_result.first.data["adminArea1"]).name if return_hash[:country_part] == 'United States' return_hash[:state_part] = Bplgeo::Constants::STATE_ABBR[mapquest_api_result.first.data["adminArea3"]] || mapquest_api_result.first.data["adminArea4"] else return_hash[:state_part] = mapquest_api_result.first.data["adminArea3"].gsub(' province', '') end return_hash[:city_part] = mapquest_api_result.first.data["adminArea5"] return_hash[:city_part] = return_hash[:city_part].gsub(' City', '') #Return New York as New York City... end #Only return if USA for now. Google is better with stuff like: 'Long Binh, Vietnam' #Also only return if there is a city if there were more than two terms passed in. Fixes: Roxbury, MA return {} unless return_hash[:country_part] == 'United States' return {} if term.split(',').length >= 2 && return_hash[:city_part].blank? return return_hash end #Final fallback is google API. The best but we are limited to 2500 requests per day unless we pay the $10k a year premium account... #Note: If google cannot find street, it will return just city/state, like for "Salem Street and Paradise Road, Swampscott, MA, 01907" #Seems like it sets a partial_match=>true in the data section... def self.parse_google_api(term, parse_term_flag=false) return_hash = {} retry_count = 3 return_hash[:original_term] = term term = Bplgeo::Standardizer.parse_for_geographic_term(term) if parse_term_flag term = Bplgeo::Standardizer.standardize_geographic_term(term) #Soviet Union returns back a place in Kazakhstan if term.blank? || term == 'Soviet Union' return {} end return_hash[:standardized_term] = term ::Geocoder.configure(:lookup => :google,:api_key => nil,:timeout => self.timeout, :always_raise => :all) google_api_result = ::Geocoder.search(term) rescue SocketError => e retry unless (retry_count -= 1).zero? else #Check if only a partial match. To avoid errors, strip out the first part and try again... #Need better way to check for street endings. See: http://pe.usps.gov/text/pub28/28apc_002.htm if google_api_result.present? if google_api_result.first.data['partial_match'] && term.split(',').length > 1 && !term.downcase.include?('street') && !term.downcase.include?('st.') && !term.downcase.include?('avenue') && !term.downcase.include?('ave.') && !term.downcase.include?('court') && !term.downcase.include?('dr.') term = term.split(',')[1..term.split(',').length-1].join(',').strip google_api_result = Geocoder.search(term) end end if google_api_result.present? #Types: street number, route, neighborhood, establishment, transit_station, bus_station google_api_result.first.data["address_components"].each do |result| if (result['types'] & ['street number', 'route', 'establishment', 'transit_station', 'bus_station']).present? || (result['types'].include?('neighborhood') && !result['types'].include?('political')) #return_hash[:term_differs_from_tgn] = true #TODO: Not implemented for Google results right now. #return_hash[:street_part] = 'TODO: Not Implemented for Google Results' return_hash[:coords] = {:latitude=>google_api_result.first.data['geometry']['location']['lat'].to_s, :longitude=>google_api_result.first.data['geometry']['location']['lng'].to_s, :combined=>google_api_result.first.data['geometry']['location']['lat'].to_s + ',' + google_api_result.first.data['geometry']['location']['lng'].to_s} elsif (result['types'] & ['country']).present? return_hash[:country_part] = result['long_name'] elsif (result['types'] & ['administrative_area_level_1']).present? return_hash[:state_part] = result['long_name'].to_ascii elsif (result['types'] & ['locality']).present? return_hash[:city_part] = result['long_name'] elsif (result['types'] & ['sublocality', 'political']).length == 2 || result['types'].include?('neighborhood') return_hash[:neighborhood_part] = result['long_name'] end end return_hash[:term_differs_from_tgn] ||= google_api_result.first.data['partial_match'] unless google_api_result.first.data['partial_match'].blank? end return return_hash end end end
no-reply/Bplgeo
test/geonames_test.rb
<filename>test/geonames_test.rb require 'test_helper' class GeonamesTest < ActiveSupport::TestCase def test_geonames_lookup_from_id if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo::Geonames.get_geonames_data('4984500') assert_equal '45.00473', result[:coords][:latitude] assert_equal '-84.14389', result[:coords][:longitude] assert_equal '45.00473,-84.14389', result[:coords][:combined] assert_equal '-84.18404', result[:coords][:box][:west] assert_equal '45.01697', result[:coords][:box][:north] assert_equal '-84.11884', result[:coords][:box][:east] assert_equal '44.98859', result[:coords][:box][:south] assert_equal 'Atlanta', result[:hier_geo][:ppla2] assert_equal 'Montmorency County', result[:hier_geo][:adm2] assert_equal 'Michigan', result[:hier_geo][:adm1] assert_equal 'United States', result[:hier_geo][:pcli] assert_equal 'North America', result[:hier_geo][:cont] assert_equal 'Earth', result[:hier_geo][:area] end end end
no-reply/Bplgeo
lib/bplgeo/geonames.rb
module Bplgeo class Geonames def self.bplgeo_config root = Rails.root || './test/dummy' env = Rails.env || 'test' @bplgeo_config ||= YAML::load(ERB.new(IO.read(File.join(root, 'config', 'bplgeo.yml'))).result)[env].with_indifferent_access end def self.geonames_username bplgeo_config[:geonames_username] || '<username>' end def self.get_geonames_data(geoname_id) max_retry = 3 sleep_time = 60 # In seconds retry_count = 0 hier_geo = {} coords = {} geonames_data = {} begin if retry_count > 0 sleep(sleep_time) end retry_count = retry_count + 1 geonames_response = Typhoeus::Request.get("http://api.geonames.org/hierarchy?username=#{self.geonames_username}&lang=en&style=FULL&geonameId=" + geoname_id) end until (geonames_response.code != 500 || retry_count == max_retry) unless geonames_response.code == 500 parsed_xml = Nokogiri::Slop(geonames_response.body) parsed_xml.geonames.geoname.each do |geoname| hier_geo[geoname.fcode.text.downcase.to_sym] = geoname.toponymName.text end #FIXME: Code4Lib lazy implementation... will get last result geoname = parsed_xml.geonames.geoname.last coords[:latitude] = geoname.lat.text coords[:longitude] = geoname.lng.text coords[:combined] = coords[:latitude] + ',' + coords[:longitude] #FIXME: Will be corrected as part of Geomash rename later this week. begin coords[:box] = {} coords[:box][:west] = geoname.bbox.west.text coords[:box][:north] = geoname.bbox.north.text coords[:box][:east] = geoname.bbox.east.text coords[:box][:south] = geoname.bbox.south.text rescue coords[:box] = {} end geonames_data[:coords] = coords geonames_data[:hier_geo] = hier_geo.present? ? hier_geo : nil end return geonames_data end def self.geonames_id_from_geo_hash(geo_hash) return nil if Bplgeo::Geonames.geonames_username == '<username>' geo_hash = geo_hash.clone max_retry = 3 sleep_time = 60 # In seconds retry_count = 0 geonames_search_array = [] return_hash = {} #Don't do both neighborhood and city! if geo_hash[:neighborhood_part].present? geonames_search_array << geo_hash[:neighborhood_part] exact_name_term = geo_hash[:neighborhood_part] elsif geo_hash[:city_part].present? geonames_search_array << geo_hash[:city_part] exact_name_term = geo_hash[:neighborhood_part] end geonames_search_array << geo_hash[:state_part] if geo_hash[:state_part].present? exact_name_term ||= geo_hash[:neighborhood_part] geonames_search_array << geo_hash[:country_part] if geo_hash[:country_part].present? exact_name_term ||= geo_hash[:country_part] geonames_search_string = geonames_search_array.join(', ') exact_name_term = geonames_search_array.first.strip begin if retry_count > 0 sleep(sleep_time) end retry_count = retry_count + 1 geonames_response = Typhoeus::Request.get("http://api.geonames.org/search?username=#{self.geonames_username}&lang=en&style=FULL&q=#{CGI.escape(geonames_search_string)}&name_equals=#{CGI.escape(exact_name_term)}&country=#{Country.find_country_by_name(geo_hash[:country_part]).alpha2}") end until (geonames_response.code != 500 || retry_count == max_retry) unless geonames_response.code == 500 parsed_xml = Nokogiri::Slop(geonames_response.body) begin raise "geonames status error message of: #{parsed_xml.to_s}" if parsed_xml.geonames.status rescue #Do nothing but FIXME to not use slop end #This is ugly and needs to be redone to achieve better recursive... if parsed_xml.geonames.totalResultsCount.text == '0' if geo_hash[:neighborhood_part].present? geo_hash_temp = geo_hash.clone geo_hash_temp[:neighborhood_part] = nil return_hash = geonames_id_from_geo_hash(geo_hash_temp) return return_hash if return_hash.present? elsif geo_hash[:city_part].present? geo_hash_temp = geo_hash.clone geo_hash_temp[:city_part] = nil return_hash = geonames_id_from_geo_hash(geo_hash_temp) return return_hash if return_hash.present? end return nil end #Exact Match ... FIXME to not use Slop if parsed_xml.geonames.geoname.class == Nokogiri::XML::Element return_hash[:id] = parsed_xml.geonames.geoname.geonameId.text return_hash[:rdf] = "http://sws.geonames.org/#{return_hash[:id]}/about.rdf" elsif parsed_xml.geonames.geoname.class ==Nokogiri::XML::NodeSet return_hash[:id] = parsed_xml.geonames.geoname.first.geonameId.text return_hash[:rdf] = "http://sws.geonames.org/#{return_hash[:id]}/about.rdf" end return_hash[:original_string_differs] = Bplgeo::Standardizer.parsed_and_original_check(geo_hash) end if geonames_response.code == 500 raise 'Geonames Server appears to not be responding for Geographic query: ' + term end return return_hash if return_hash.present? return nil end end end
no-reply/Bplgeo
bplgeo.gemspec
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "bplgeo/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "bplgeo" s.version = Bplgeo::VERSION s.authors = ["Boston Public Library"] s.email = ["<EMAIL>"] s.homepage = "http://www.bpl.org" s.summary = "Parse string for potential geographic matches and return that data along with the TGN ID and Geonames ID." s.description = "Parse string for potential geographic matches and return that data along with the TGN ID and Geonames ID." s.files = Dir["{app,config,db,lib}/**/*", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.1" s.add_dependency "countries" s.add_dependency "geocoder" s.add_dependency 'unidecoder' s.add_dependency 'typhoeus' s.add_dependency 'nokogiri' s.add_dependency 'htmlentities' s.add_dependency 'sparql' s.add_development_dependency "sqlite3" end
no-reply/Bplgeo
test/standardizer_test.rb
require 'test_helper' class ParserTest < ActiveSupport::TestCase def test_dedup_geo sample_array = ['Saigon, Vietnam', 'Saigon (Vietnam)', 'Vietnam', 'Vietnam, Party'] result = Bplgeo::Standardizer.dedup_geo(sample_array) assert_equal ['Saigon, Vietnam', 'Vietnam', 'Vietnam, Party'], result result = Bplgeo::Standardizer.dedup_geo(sample_array, true) assert_equal ['Saigon, Vietnam', 'Vietnam, Party'], result sample_array << 'Some Place, Vietnam' result = Bplgeo::Standardizer.dedup_geo(sample_array) assert_equal ['Saigon, Vietnam', 'Vietnam', 'Vietnam, Party', 'Some Place, Vietnam'], result result = Bplgeo::Standardizer.dedup_geo(sample_array, true) assert_equal ['Saigon, Vietnam', 'Vietnam, Party', 'Some Place, Vietnam'], result #sample_array << 'Some Place, Vietnam, Saigon' #result = Bplgeo::Standardizer.dedup_geo(sample_array, true) #assert_equal ['Some Place, Vietnam, Saigon'], result end end
no-reply/Bplgeo
lib/bplgeo.rb
module Bplgeo require "bplgeo/constants" require "bplgeo/parser" require "bplgeo/standardizer" require "bplgeo/tgn" require "bplgeo/geonames" require "bplgeo/town_lookup" require "geocoder" require "countries" require "unidecoder" require "typhoeus" require "nokogiri" require "htmlentities" def self.parse(term,parse_term=false) return {} if term.blank? return_hash = Bplgeo::Parser.parse_mapquest_api(term, parse_term) if return_hash.blank? return_hash = Bplgeo::Parser.parse_bing_api(term, parse_term) end if return_hash.blank? return_hash = Bplgeo::Parser.parse_google_api(term, parse_term) end if return_hash[:country_part].present? #FIXME return_hash[:tgn] = Bplgeo::TGN.tgn_id_from_geo_hash(return_hash) if return_hash[:tgn].blank? geo_hash_temp = Bplgeo::Standardizer.try_with_entered_names(return_hash) return_hash[:tgn] = Bplgeo::TGN.tgn_id_from_geo_hash(geo_hash_temp) if geo_hash_temp.present? if return_hash[:tgn].blank? && return_hash[:neighborhood_part].present? geo_hash_temp = return_hash.clone geo_hash_temp[:neighborhood_part] = nil geo_hash_temp[:original_string_differs] = true return_hash[:tgn] = Bplgeo::TGN.tgn_id_from_geo_hash(geo_hash_temp) return_hash[:tgn][:original_string_differs] = true if return_hash[:tgn].present? elsif return_hash[:city_part].present? && return_hash[:tgn].blank? geo_hash_temp = return_hash.clone geo_hash_temp[:city_part] = nil geo_hash_temp[:original_string_differs] = true return_hash[:tgn] = Bplgeo::TGN.tgn_id_from_geo_hash(geo_hash_temp) return_hash[:tgn][:original_string_differs] = true if return_hash[:tgn].present? end end return_hash[:geonames] = Bplgeo::Geonames.geonames_id_from_geo_hash(return_hash) end return return_hash end end
no-reply/Bplgeo
test/tgn_test.rb
require 'test_helper' class TGNTest < ActiveSupport::TestCase def test_tgn_lookup_from_id if Bplgeo::TGN.tgn_enabled == 'true' result = Bplgeo::TGN.get_tgn_data('2051159') assert_equal '45', result[:coords][:latitude] assert_equal '-84.1333', result[:coords][:longitude] assert_equal '45,-84.1333', result[:coords][:combined] assert_equal 'Atlanta', result[:hier_geo][:city] assert_equal 'Montmorency', result[:hier_geo][:county] assert_equal 'Michigan', result[:hier_geo][:state] assert_equal 'United States', result[:hier_geo][:country] assert_equal 'North and Central America', result[:hier_geo][:continent] end end end
no-reply/Bplgeo
test/town_lookup_test.rb
require 'test_helper' class TownLookupTest < ActiveSupport::TestCase def test_MA_lookup result = Bplgeo::TownLookup.state_town_lookup('MA', "This test was written in Boston, MA.") assert_equal '7013445', result result = Bplgeo::TownLookup.state_town_lookup('MA', "This test was written in East Boston, MA.") assert_equal '7015009', result end end
no-reply/Bplgeo
lib/bplgeo/tgn.rb
<filename>lib/bplgeo/tgn.rb module Bplgeo class TGN def self.bplgeo_config root = Rails.root || './test/dummy' env = Rails.env || 'test' @bplgeo_config ||= YAML::load(ERB.new(IO.read(File.join(root, 'config', 'bplgeo.yml'))).result)[env].with_indifferent_access end def self.tgn_enabled bplgeo_config[:tgn_enabled] || true end =begin 81010/nation 81175/state 81165/region 84251/neighborhood 83002/inhabited place nations <http://vocab.getty.edu/tgn/7012149> <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300128207> States (political divisions): <http://vocab.getty.edu/tgn/7007517> <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000776> . Counties: (Suffolk - http://vocab.getty.edu/aat/300000771) <http://vocab.getty.edu/tgn/1002923> <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000771> . Neighborhood: (Boston) <http://vocab.getty.edu/tgn/7013445> <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347> . Provinces: http://vocab.getty.edu/aat/300000774 Departments: http://vocab.getty.edu/aat/300000772 Governates: http://vocab.getty.edu/aat/300235093 Territories: http://vocab.getty.edu/aat/300135982 + http://vocab.getty.edu/resource/getty/search?q=territory&luceneIndex=Brief&indexDataset=AAT&_form=%2Fresource%2Fgetty%2Fsearch dependent state: http://vocab.getty.edu/aat/300387176 union territory: http://vocab.getty.edu/aat/300387122 national district: http://vocab.getty.edu/aat/300387081 Roxbury: http://vocab.getty.edu/tgn/7015002.json #South Carolina - http://vocab.getty.edu/tgn/7007712 SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> 7007712 . ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_country . { SELECT ?parent_country ?identifier_country ?aat_place_id WHERE { ?parent_country <http://purl.org/dc/elements/1.1/identifier> ?identifier_country . ?parent_country <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_place_id . ?parent_country <http://www.w3.org/2000/01/rdf-schema#label> ?country_label . } GROUP BY ?parent_country } } GROUP BY ?object_identifier primary_tgn_response = Typhoeus::Request.get("http://vocab.getty.edu/tgn/#{tgn_id}.json") when 'http://vocab.getty.edu/ontology#placeTypePreferred' place_type_base[:aat_id] = ntriple['Object']['value'] when 'http://www.w3.org/2004/02/skos/core#prefLabel' if ntriple['Object']['xml:lang'].present? && ntriple['Object']['xml:lang'] == 'en' place_type_base[:label_en] = ntriple['Object']['value'] else if ntriple['Object']['xml:lang'].blank? place_type_base[:label_default] = ntriple['Object']['value'] tgn_main_term_info = {} broader_place_type_list = ["http://vocab.getty.edu/tgn/"#{tgn_id}] primary_tgn_response = Typhoeus::Request.get("http://vocab.getty.edu/download/json", :params=>{:uri=>"http://vocab.getty.edu/tgn/#{tgn_id}.json"}) as_json_tgn_response = JSON.parse(primary_tgn_response.body) as_json_tgn_response['results']['bindings'].each do |ntriple| case ntriple['Predicate']['value'] when 'http://www.w3.org/2004/02/skos/core#prefLabel' if ntriple['Object']['xml:lang'].present? && ntriple['Object']['xml:lang'] == 'en' tgn_main_term_info[:label_en] = ntriple['Object']['value'] elsif ntriple['Object']['xml:lang'].blank? tgn_main_term_info[:label_default] = ntriple['Object']['value'] end when 'http://vocab.getty.edu/ontology#placeTypePreferred' tgn_main_term_info[:aat_place] = ntriple['Object']['value'] when 'http://vocab.getty.edu/ontology#broaderPreferredExtended' broader_place_type_list << ntriple['Object']['value'] end end query = "SELECT ?identifier_place ?place_label_default ?place_label_en ?aat_pref WHERE {" broader_place_type_list.each do |place_uri| query += %{{<#{place_uri}> <http://purl.org/dc/elements/1.1/identifier> ?identifier_place . OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_en FILTER langMatches( lang(?place_label_en), "en" ) } OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_default FILTER langMatches( lang(?place_label_default), "" ) } <#{place_uri}> <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_pref } UNION } end query = query[0..-12] query += ". } GROUP BY ?identifier_place ?place_label_default ?place_label_en ?aat_pref" tgn_response_for_aat = Typhoeus::Request.get("http://vocab.getty.edu/sparql.json", :params=>{:query=>query}) as_json_tgn_response_for_aat = JSON.parse(tgn_response_for_aat.body) as_json_tgn_response_for_aat["results"]["bindings"].each do |aat_response| #aat_response['identifier_place']['value'] #aat_response['place_label_default']['value'] #.... end EXAMPLE SPARQL: SELECT ?identifier_place ?place_label_default ?place_label_en ?aat_pref WHERE { {<http://vocab.getty.edu/tgn/1000001> <http://purl.org/dc/elements/1.1/identifier> ?identifier_place . OPTIONAL {<http://vocab.getty.edu/tgn/1000001> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_en FILTER langMatches( lang(?place_label_en), "en" ) } OPTIONAL {<http://vocab.getty.edu/tgn/1000001> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_default FILTER langMatches( lang(?place_label_default), "" ) } <http://vocab.getty.edu/tgn/1000001> <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_pref } UNION {<http://vocab.getty.edu/tgn/7012149> <http://purl.org/dc/elements/1.1/identifier> ?identifier_place . OPTIONAL {<http://vocab.getty.edu/tgn/7012149> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_en FILTER langMatches( lang(?place_label_en), "en" ) } OPTIONAL {<http://vocab.getty.edu/tgn/7012149> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_default FILTER langMatches( lang(?place_label_default), "" ) } <http://vocab.getty.edu/tgn/7012149> <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_pref } UNION {<http://vocab.getty.edu/tgn/7029392> <http://purl.org/dc/elements/1.1/identifier> ?identifier_place . OPTIONAL {<http://vocab.getty.edu/tgn/7029392> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_en FILTER langMatches( lang(?place_label_en), "en" ) } OPTIONAL {<http://vocab.getty.edu/tgn/7029392> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_default FILTER langMatches( lang(?place_label_default), "" ) } <http://vocab.getty.edu/tgn/7012149> <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_pref } . } GROUP BY ?identifier_place ?place_label_default ?place_label_en ?aat_pref =end def self.get_tgn_data(tgn_id) return nil if Bplgeo::TGN.tgn_enabled != true tgn_id = tgn_id.strip tgn_main_term_info = {} broader_place_type_list = [] primary_tgn_response = Typhoeus::Request.get("http://vocab.getty.edu/download/json", :params=>{:uri=>"http://vocab.getty.edu/tgn/#{tgn_id}.json"}) return nil if(primary_tgn_response.response_code == 404) #Couldn't find TGN... FIXME: additional check needed if TGN is down? as_json_tgn_response = JSON.parse(primary_tgn_response.body) #There is a bug with some TGN JSON files currently. Example: http://vocab.getty.edu/tgn/7014203.json . Per an email # with Getty, this is a hackish workaround for now. if(as_json_tgn_response['results'].blank?) query = %{ PREFIX tgn: <http://vocab.getty.edu/tgn/> PREFIX gvp: <http://vocab.getty.edu/ontology#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX dct: <http://purl.org/dc/terms/> PREFIX bibo: <http://purl.org/ontology/bibo/> PREFIX skosxl: <http://www.w3.org/2008/05/skos-xl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX iso: <http://purl.org/iso25964/skos-thes#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX schema: <http://schema.org/> CONSTRUCT { ?s ?p1 ?o1. ?ac ?p2 ?o2. ?t ?p3 ?o3. ?ss ?p4 ?o4. ?ts ?p6 ?o6. ?st ?p7 ?o7. ?ar ?p8 ?o8. ?l1 ?p9 ?o9. ?l2 ?pA ?oA. ?pl ?pB ?oB. ?ge ?pC ?oC. } WHERE { BIND (tgn:#{tgn_id} as ?s) {?s ?p1 ?o1 FILTER(!isBlank(?o1) && !(?p1 in (gvp:narrowerExtended, skos:narrowerTransitive, skos:semanticRelation)))} UNION {?s skos:changeNote ?ac. ?ac ?p2 ?o2} UNION {?s dct:source ?ss. ?ss a bibo:DocumentPart. ?ss ?p4 ?o4} UNION {?s skos:scopeNote|skosxl:prefLabel|skosxl:altLabel ?t. {?t ?p3 ?o3 FILTER(!isBlank(?o3))} UNION {?t dct:source ?ts. ?ts a bibo:DocumentPart. ?ts ?p6 ?o6}} UNION {?st rdf:subject ?s. ?st ?p7 ?o7} UNION {?s skos:member/^rdf:first ?l1. ?l1 ?p9 ?o9} UNION {?s iso:subordinateArray ?ar FILTER NOT EXISTS {?ar skosxl:prefLabel ?t1}. {?ar ?p8 ?o8} UNION {?ar skos:member/^rdf:first ?l2. ?l2 ?pA ?oA}} UNION {?s foaf:focus ?pl. {?pl ?pB ?oB} UNION {?pl schema:geo ?ge. ?ge ?pC ?oC}} } } query = query.squish primary_tgn_response = Typhoeus::Request.post("http://vocab.getty.edu/sparql.json", :body=>{:query=>query}) as_json_tgn_response = JSON.parse(primary_tgn_response.body) end #FIXME: Temporary hack to determine more cases of non-blank/english place name conflicts that require resolution. label_remaining_check = false as_json_tgn_response['results']['bindings'].each do |ntriple| case ntriple['Predicate']['value'] when 'http://www.w3.org/2004/02/skos/core#prefLabel' if ntriple['Object']['xml:lang'].present? && ntriple['Object']['xml:lang'] == 'en' tgn_main_term_info[:label_en] = ntriple['Object']['value'] elsif ntriple['Object']['xml:lang'].present? && ntriple['Object']['xml:lang'] == 'zh-latn-pinyin' tgn_main_term_info[:label_other] = ntriple['Object']['value'] elsif ntriple['Object']['xml:lang'].blank? tgn_main_term_info[:label_default] = ntriple['Object']['value'] else label_remaining_check = true if tgn_main_term_info[:label_remaining].present? tgn_main_term_info[:label_remaining] = ntriple['Object']['value'] end when 'http://www.w3.org/2004/02/skos/core#altLabel' if ntriple['Object']['xml:lang'].present? && ntriple['Object']['xml:lang'] == 'en' tgn_main_term_info[:label_alt] = ntriple['Object']['value'] end when 'http://vocab.getty.edu/ontology#placeTypePreferred' tgn_main_term_info[:aat_place] = ntriple['Object']['value'] when 'http://schema.org/latitude' tgn_main_term_info[:latitude] = ntriple['Object']['value'] when 'http://schema.org/longitude' tgn_main_term_info[:longitude] = ntriple['Object']['value'] when 'http://vocab.getty.edu/ontology#broaderPreferredExtended' broader_place_type_list << ntriple['Object']['value'] end end # coordinates coords = nil if tgn_main_term_info[:latitude].present? coords = {} coords[:latitude] = tgn_main_term_info[:latitude] coords[:longitude] = tgn_main_term_info[:longitude] coords[:combined] = tgn_main_term_info[:latitude] + ',' + tgn_main_term_info[:longitude] end hier_geo = {} #Default term to best label language... tgn_term = tgn_main_term_info[:label_en] tgn_term ||= tgn_main_term_info[:label_default] tgn_term ||= tgn_main_term_info[:label_other] tgn_term ||= tgn_main_term_info[:label_alt] if tgn_term.blank? if label_remaining_check raise "Could not determine a single label for TGN: " + tgn_id else tgn_term = tgn_main_term_info[:label_remaining] end end tgn_term_type = tgn_main_term_info[:aat_place].split('/').last #Initial Term if tgn_term.present? && tgn_term_type.present? case tgn_term_type when '300128176' #continent hier_geo[:continent] = tgn_term when '300128207' #nations hier_geo[:country] = tgn_term when '300000774' #province hier_geo[:province] = tgn_term when '300236112', '300182722', '300387194', '300387052' #region, union, semi-independent political entity hier_geo[:region] = tgn_term when '300000776', '300000772', '300235093' #state, department, governorate hier_geo[:state] = tgn_term when '300387081' #national district if tgn_term == 'District of Columbia' hier_geo[:state] = tgn_term else hier_geo[:territory] = tgn_term end when '300135982', '300387176', '300387122' #territory, dependent state, union territory hier_geo[:territory] = tgn_term when '300000771' #county hier_geo[:county] = tgn_term when '300008347' #inhabited place hier_geo[:city] = tgn_term when '300000745' #neighborhood hier_geo[:city_section] = tgn_term when '300008791', '300387062' #island hier_geo[:island] = tgn_term when '300387575', '300387346', '300167671', '300387178', '300387082' #'81101/area', '22101/general region', '83210/deserted settlement', '81501/historical region', '81126/national division' hier_geo[:area] = tgn_term else non_hier_geo = tgn_term end #Broader places #FIXME: could parse xml:lang instead of the three optional clauses now... didn't expect places to lack a default preferred label. query = "SELECT ?identifier_place ?place_label_default ?place_label_en ?place_label_remaining ?aat_pref WHERE {" broader_place_type_list.each do |place_uri| query += %{{<#{place_uri}> <http://purl.org/dc/elements/1.1/identifier> ?identifier_place . OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_en FILTER langMatches( lang(?place_label_en), "en" ) } OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_default FILTER langMatches( lang(?place_label_default), "" ) } OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_latn_pinyin FILTER langMatches( lang(?place_label_latn_pinyin), "zh-latn-pinyin" ) } OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#altLabel> ?place_label_alt FILTER langMatches( lang(?place_label_alt), "en" ) } OPTIONAL {<#{place_uri}> <http://www.w3.org/2004/02/skos/core#prefLabel> ?place_label_remaining FILTER(!langMatches( lang(?place_label_remaining), "" ) && !langMatches( lang(?place_label_remaining), "en" ) && !langMatches( lang(?place_label_remaining), "zh-latn-pinyin" )) } <#{place_uri}> <http://vocab.getty.edu/ontology#placeTypePreferred> ?aat_pref } UNION } end query = query[0..-12] query += ". } GROUP BY ?identifier_place ?place_label_default ?place_label_en ?place_label_latn_pinyin ?place_label_alt ?place_label_remaining ?aat_pref" query = query.squish tgn_response_for_aat = Typhoeus::Request.post("http://vocab.getty.edu/sparql.json", :body=>{:query=>query}) as_json_tgn_response_for_aat = JSON.parse(tgn_response_for_aat.body) as_json_tgn_response_for_aat["results"]["bindings"].each do |aat_response| tgn_term_type = aat_response['aat_pref']['value'].split('/').last if aat_response['place_label_en'].present? && aat_response['place_label_en']['value'] != '-' tgn_term = aat_response['place_label_en']['value'] elsif aat_response['place_label_default'].present? && aat_response['place_label_default']['value'] != '-' tgn_term = aat_response['place_label_default']['value'] elsif aat_response['place_label_latn_pinyin'].present? && aat_response['place_label_latn_pinyin']['value'] != '-' tgn_term = aat_response['place_label_latn_pinyin']['value'] elsif aat_response['place_label_alt'].present? && aat_response['place_label_alt']['value'] != '-' tgn_term = aat_response['place_label_alt']['value'] else tgn_term = aat_response['place_label_remaining']['value'] end case tgn_term_type when '300128176' #continent hier_geo[:continent] = tgn_term when '300128207' #nation hier_geo[:country] = tgn_term when '300000774' #province hier_geo[:province] = tgn_term when '300236112', '300182722', '300387194', '300387052' #region, union, semi-independent political entity hier_geo[:region] = tgn_term when '300000776', '300000772', '300235093' #state, department, governorate hier_geo[:state] = tgn_term when '300387081' #national district if tgn_term == 'District of Columbia' hier_geo[:state] = tgn_term else hier_geo[:territory] = tgn_term end when '300135982', '300387176', '300387122' #territory, dependent state, union territory hier_geo[:territory] = tgn_term when '300000771' #county hier_geo[:county] = tgn_term when '300008347' #inhabited place hier_geo[:city] = tgn_term when '300000745' #neighborhood hier_geo[:city_section] = tgn_term when '300008791', '300387062' #island hier_geo[:island] = tgn_term when '300387575', '300387346', '300167671', '300387178', '300387082' #'81101/area', '22101/general region', '83210/deserted settlement', '81501/historical region', '81126/national division' hier_geo[:area] = tgn_term end end tgn_data = {} tgn_data[:coords] = coords tgn_data[:hier_geo] = hier_geo.length > 0 ? hier_geo : nil tgn_data[:non_hier_geo] = non_hier_geo ? non_hier_geo : nil else tgn_data = nil end return tgn_data end def self.tgn_id_from_geo_hash(geo_hash) return nil if Bplgeo::TGN.tgn_enabled != true geo_hash = geo_hash.clone max_retry = 3 sleep_time = 60 # In seconds retry_count = 0 return_hash = {} state_part = geo_hash[:state_part] country_code = Bplgeo::Constants::COUNTRY_TGN_LOOKUP[geo_hash[:country_part]][:tgn_id] unless Bplgeo::Constants::COUNTRY_TGN_LOOKUP[geo_hash[:country_part]].blank? country_code ||= '' country_part = Bplgeo::Constants::COUNTRY_TGN_LOOKUP[geo_hash[:country_part]][:tgn_country_name] unless Bplgeo::Constants::COUNTRY_TGN_LOOKUP[geo_hash[:country_part]].blank? country_part ||= geo_hash[:country_part] country_part ||= '' city_part = geo_hash[:city_part] neighborhood_part = geo_hash[:neighborhood_part] if city_part.blank? && state_part.blank? # Limit to nations query = %{SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> ?object_identifier . ?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300128207> . ?x <http://www.w3.org/2004/02/skos/core#prefLabel> ?object_label . FILTER regex(?object_label, "^#{country_part}$", "i" ) }} elsif state_part.present? && city_part.blank? && country_code == 7012149 #Limit to states query = %{SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> ?object_identifier . ?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000776> . ?x <http://www.w3.org/2000/01/rdf-schema#label> ?object_label . FILTER regex(?object_label, "^#{state_part}$", "i" ) ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> <http://vocab.getty.edu/tgn/7012149> . }} elsif state_part.present? && city_part.blank? #Limit to regions query = %{SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> ?object_identifier . {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000774>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000772>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300235093>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300135982>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387176>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387122>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000776>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300236112>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347>} UNION {?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387081>} . ?x <http://www.w3.org/2000/01/rdf-schema#label> ?object_label . FILTER regex(?object_label, "^#{state_part}$", "i" ) ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_country . { SELECT ?parent_country ?identifier_country WHERE { ?parent_country <http://purl.org/dc/elements/1.1/identifier> ?identifier_country . ?parent_country <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300128207> . ?parent_country <http://www.w3.org/2000/01/rdf-schema#label> ?country_label . FILTER regex(?country_label, "^#{country_part}$", "i" ) } } } GROUP BY ?object_identifier } #FIXME Temporary: For Bplgeo.parse('Aknīste (Latvia)', true), seems to be a neighborhood placed in state # {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347>} UNION elsif state_part.present? && city_part.present? && neighborhood_part.blank? #Limited to only inhabited places at the moment... query = %{SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> ?object_identifier . ?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347> . ?x <http://www.w3.org/2000/01/rdf-schema#label> ?object_label . FILTER regex(?object_label, "^#{city_part}$", "i" ) ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_country . { SELECT ?parent_country ?identifier_country WHERE { ?parent_country <http://purl.org/dc/elements/1.1/identifier> ?identifier_country . ?parent_country <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300128207> . ?parent_country <http://www.w3.org/2000/01/rdf-schema#label> ?country_label . FILTER regex(?country_label, "^#{country_part}$", "i" ) } } ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_state . { SELECT ?parent_state ?identifier_state WHERE { ?parent_state <http://purl.org/dc/elements/1.1/identifier> ?identifier_state . {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000774>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000772>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300235093>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300135982>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387176>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387122>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000776>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300236112>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387081>} . ?parent_state <http://www.w3.org/2000/01/rdf-schema#label> ?state_label . FILTER regex(?state_label, "^#{state_part}$", "i" ) } } } GROUP BY ?object_identifier } elsif state_part.present? && city_part.present? && neighborhood_part.present? #Limited to only to neighborhoods currently... query = %{SELECT ?object_identifier WHERE { ?x <http://purl.org/dc/elements/1.1/identifier> ?object_identifier . ?x <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000745> . ?x <http://www.w3.org/2000/01/rdf-schema#label> ?object_label . FILTER regex(?object_label, "^#{neighborhood_part}$", "i" ) ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_country . { SELECT ?parent_country ?identifier_country WHERE { ?parent_country <http://purl.org/dc/elements/1.1/identifier> ?identifier_country . ?parent_country <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300128207> . ?parent_country <http://www.w3.org/2000/01/rdf-schema#label> ?country_label . FILTER regex(?country_label, "^#{country_part}$", "i" ) } } ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_state . { SELECT ?parent_state ?identifier_state WHERE { ?parent_state <http://purl.org/dc/elements/1.1/identifier> ?identifier_state . {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000774>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000772>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300235093>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300135982>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387176>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387122>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300000776>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300236112>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347>} UNION {?parent_state <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300387081>} . ?parent_state <http://www.w3.org/2000/01/rdf-schema#label> ?state_label . FILTER regex(?state_label, "^#{state_part}$", "i" ) } } ?x <http://vocab.getty.edu/ontology#broaderPreferredExtended> ?parent_city . { SELECT ?parent_city ?identifier_city WHERE { ?parent_city <http://purl.org/dc/elements/1.1/identifier> ?identifier_city . ?parent_city <http://vocab.getty.edu/ontology#placeTypePreferred> <http://vocab.getty.edu/aat/300008347> . ?parent_city <http://www.w3.org/2000/01/rdf-schema#label> ?city_label . FILTER regex(?city_label, "^#{city_part}$", "i" ) } } } GROUP BY ?object_identifier } else return nil end begin if retry_count > 0 sleep(sleep_time) end retry_count = retry_count + 1 query = query.squish tgn_response = Typhoeus::Request.get("http://vocab.getty.edu/sparql.json", :params=>{:query=>query}) end until (tgn_response.code != 500 || retry_count == max_retry) unless tgn_response.code == 500 as_json = JSON.parse(tgn_response.body) #This is ugly and needs to be redone to achieve better recursive... if as_json["results"]["bindings"].present? && as_json["results"]["bindings"].first["object_identifier"].present? return_hash[:id] = as_json["results"]["bindings"].first["object_identifier"]["value"] return_hash[:rdf] = "http://vocab.getty.edu/tgn/#{return_hash[:id]}.rdf" else return nil end end if tgn_response.code == 500 raise 'TGN Server appears to not be responding for Geographic query: ' + query end if return_hash.present? return_hash[:original_string_differs] = Bplgeo::Standardizer.parsed_and_original_check(geo_hash) return return_hash else return nil end end end end
no-reply/Bplgeo
test/parser_test.rb
require 'test_helper' class ParserTest < ActiveSupport::TestCase def test_google_parser result = Bplgeo::Parser.parse_google_api('Boston, MA') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal nil, result[:street_part] result = Bplgeo::Parser.parse_google_api('700 Boylston St, Boston, MA 02116') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] result = Bplgeo::Parser.parse_google_api('Roxbury (Boston, Mass.)') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal 'Roxbury', result[:neighborhood_part] assert_equal nil, result[:street_part] #FIXME!!! Is this alright? #result = Bplgeo::Parser.parse_google_api('201 Dowman Dr., Atlanta, GA 30322') #assert_equal 'Atlanta', result[:city_part] #assert_equal 'Georgia', result[:state_part] #assert_equal 'United States', result[:country_part] #assert_equal 'true', result[:term_differs_from_tgn] end end
no-reply/Bplgeo
test/bplgeo_test.rb
require 'test_helper' #Historical stuff like Jews--Soviet Union--History--Catalogs ? # Registers of births, etc.--Canada, Western totally borked #Synagogues--Germany--Baden-Württemberg--Directories -> doesn't match as google returns Baden-Württemberg as #Baden-Wurttemberg . No matches http://vocab.getty.edu/tgn/7003692 class BplgeoTest < ActiveSupport::TestCase def test_parse_with_flag result = Bplgeo.parse('Abbeville (France)--History--20th century.', true) assert_equal 'Abbeville', result[:city_part] assert_equal 'Picardy', result[:state_part] assert_equal 'France', result[:country_part] assert_equal nil, result[:street_part] assert_equal '7010587', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal true, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '2987374', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal true, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' #Slight variation problem with neighborhood: 11. Bezirk (Vienna, Austria)--Biography result = Bplgeo.parse('15. Bezirk (Rudolfsheim-Fünfhaus, Vienna, Austria)--Exhibitions', true) assert_equal 'Vienna', result[:city_part] assert_equal 'Vienna', result[:state_part] assert_equal 'Austria', result[:country_part] assert_equal 'Rudolfsheim-Fünfhaus', result[:neighborhood_part] assert_equal nil, result[:street_part] assert_equal '7003321', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal true, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '2779138', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal true, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('Synagogues--Germany--Baden-Württemberg--Directories', true) assert_equal nil, result[:city_part] assert_equal 'Baden-Wurttemberg', result[:state_part] assert_equal 'Germany', result[:country_part] assert_equal nil, result[:neighborhood_part] assert_equal nil, result[:street_part] assert_equal '7003692', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal true, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '2953481', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal true, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' end def test_parse_with_no_flag result = Bplgeo.parse('Boston, MA') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal nil, result[:street_part] assert_equal '7013445', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '4930956', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('New York, NY') assert_equal 'New York', result[:city_part] assert_equal 'New York', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal nil, result[:street_part] assert_equal '7007567', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '5128581', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('Washington, DC') assert_equal 'Washington', result[:city_part] assert_equal 'District of Columbia', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal nil, result[:street_part] assert_equal '7013962', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '4140963', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('Roxbury (Boston, Mass.)') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal 'Roxbury', result[:neighborhood_part] assert_equal nil, result[:street_part] assert_equal '7015002', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true #FIXME? assert_equal '4949151', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('Roxbury, Mass.') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal 'Roxbury', result[:neighborhood_part] assert_equal nil, result[:street_part] assert_equal '7015002', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true #FIXME? assert_equal '4949151', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' result = Bplgeo.parse('Vietnam') assert_equal nil, result[:city_part] assert_equal nil, result[:state_part] assert_equal 'Vietnam', result[:country_part] assert_equal nil, result[:neighborhood_part] assert_equal '1000145', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal nil, result[:street_part] assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true result = Bplgeo.parse('Soviet Union') assert_equal nil, result[:city_part] assert_equal nil, result[:state_part] assert_equal nil, result[:country_part] assert_equal nil, result[:neighborhood_part] assert_equal nil, result[:tgn] assert_equal nil, result[:street_part] result = Bplgeo.parse('Fenway (Boston, Mass.)') assert_equal 'Boston', result[:city_part] assert_equal 'Massachusetts', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal 'Fenway/Kenmore', result[:neighborhood_part] assert_equal '7013445', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal nil, result[:street_part] assert_equal true, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true #Should find the Michigan Atlanta over the Georgia Atlanta #State part from an API giving me Atlanta???? result = Bplgeo.parse('Atlanta, MI') assert_equal 'Atlanta', result[:city_part] assert_equal 'Michigan', result[:state_part] assert_equal 'United States', result[:country_part] assert_equal nil, result[:neighborhood_part] assert_equal '2051159', result[:tgn][:id] if Bplgeo::TGN.tgn_enabled == true assert_equal false, result[:tgn][:original_string_differs] if Bplgeo::TGN.tgn_enabled == true assert_equal '4984500', result[:geonames][:id] if Bplgeo::Geonames.geonames_username != '<username>' assert_equal false, result[:geonames][:original_string_differs] if Bplgeo::Geonames.geonames_username != '<username>' end end
no-reply/Bplgeo
lib/bplgeo/town_lookup.rb
module Bplgeo class TownLookup #Only returns one result for now... #Need to avoid cases like "Boston" and "East Boston" def self.state_town_lookup(state_key, string) return_tgn_id = nil matched_terms_count = 0 matching_towns = Bplgeo::Constants::STATE_TOWN_TGN_IDS[state_key.to_sym].select {|hash| string.include?(hash[:location_name])} matching_towns.each do |matching_town| if matching_town[:location_name].split(' ').length > matched_terms_count return_tgn_id = matching_town[:tgn_id] matched_terms_count = matching_town[:location_name].split(' ').length end end return return_tgn_id end end end
no-reply/Bplgeo
lib/bplgeo/standardizer.rb
module Bplgeo class Standardizer #Take a subject string and look for potential geographic terms. def self.parse_for_geographic_term(term) geo_term = '' #Likely too long to be an address... some fields have junk with an address string... if term.length > 125 return '' end state_abbr_list = ['Mass'] state_name_list = [] country_name_list = [] #Countries gem of https://github.com/hexorx/countries Country.new('US').states.each do |state_abbr, state_names| state_abbr_list << ' ' + state_abbr state_name_list << state_names["name"] end Country.all.each do |country_name_abbr_pair| country_name_list << country_name_abbr_pair.first end #Parsing a subject geographic term. if term.include?('--') term.split('--').each_with_index do |split_term, index| if state_name_list.any? { |state| split_term.include? state } || country_name_list.any? { |country| split_term.include? country } geo_term = term.split('--')[index..term.split('--').length-1].reverse!.join(',') elsif state_abbr_list.any? { |abbr| split_term.include? abbr } geo_term = split_term end end #Other than a '--' field #Experimental... example: Palmer (Mass) - history or Stores (retail trade) - Palmer, Mass elsif term.include?(' - ') term.split(' - ').each do |split_term| if state_name_list.any? { |state| split_term.include? state } || state_abbr_list.any? { |abbr| split_term.include? abbr } || country_name_list.any? { |country| split_term.include? country } geo_term = split_term end end else if state_name_list.any? { |state| term.include? state } || state_abbr_list.any? { |abbr| term.include? abbr } || country_name_list.any? { |country| term.include? country } geo_term = term end end return geo_term end #Make a string in a standard format. def self.standardize_geographic_term(geo_term) geo_term = geo_term.clone #Don't change original #Remove common junk terms Bplgeo::Constants::JUNK_TERMS.each { |term| geo_term.gsub!(term, '') } #Strip any leading periods or commas from junk terms geo_term = geo_term.gsub(/^[\.,]+/, '').strip #Replace any four TGN dashes from removing a junk term geo_term = geo_term.gsub('----', '--') #Replace any semicolons with commas... possible strip them? geo_term = geo_term.gsub(';', ',') #Terms in paranthesis will cause some geographic parsers to freak out. Switch to commas instead. if geo_term.match(/[\(\)]+/) #Attempt to fix address if something like (word) if geo_term.match(/ \(+.*\)+/) #Make this replacement better? geo_term = geo_term.gsub(/ *\((?=[\S ]+\))/,', ') geo_term = geo_term.gsub(')', '') #Else skip this as data returned likely will be unreliable for now... FIXME when use case occurs. else return nil end end return geo_term end #Attempt to dedup a list of geographic areas. #FIXME: Horrendous first pass. #Aggresive flag removes less specific matches. IE. ['Hanoi, Vietnam' and 'Vietnam'] would return just ['Hanoi, Vietnam'] def self.dedup_geo(geo_list, aggressive=false) geo_list = geo_list.clone base_word_geo_list = [] geo_list.each do |geo_term| geo_term = geo_term.gsub('(','').gsub(')','').gsub('.','').gsub(',','').gsub(';','') #Remove common junk terms Bplgeo::Constants::JUNK_TERMS.each { |term| geo_term.gsub!(term, '') } geo_term = geo_term.squish base_word_geo_list << geo_term end indexes_to_remove = [] 0.upto base_word_geo_list.size-1 do |index| matched_words_count = [] current_best_term = geo_list[index] current_best_term_index = index base_word_geo_list[index].split(' ').each { |word| (index+1).upto base_word_geo_list.size-1 do |inner_index| if base_word_geo_list[inner_index].split(' ').any? { |single_word| single_word == word } matched_words_count[inner_index] ||= 0 matched_words_count[inner_index] = matched_words_count[inner_index] + 1 end end } matched_words_count.each_with_index do |matched_count, matched_index| matched_count ||= 0 if (matched_count == base_word_geo_list[matched_index].split(' ').size) && ((base_word_geo_list[matched_index].split(' ').size < base_word_geo_list[index].split(' ').size && aggressive) || (base_word_geo_list[matched_index].split(' ').size == base_word_geo_list[index].split(' ').size)) if current_best_term.split(',').size < geo_list[matched_index].split(',').size || (current_best_term.size+1 < geo_list[matched_index].size && !geo_list[matched_index].include?('(')) current_best_term = geo_list[matched_index] indexes_to_remove << current_best_term_index current_best_term_index = matched_index else indexes_to_remove << matched_index end end end end indexes_to_remove.each do |removal_index| geo_list[removal_index] = nil end return geo_list.compact end def self.parsed_and_original_check(geo_hash) term = geo_hash[:standardized_term] if geo_hash[:street_part].present? || geo_hash[:coords].present? return true end #Keep original string if three parts at least or if there is a number in the term. #TODO: Make this better! if (term.split(',').length >= 3 && geo_hash[:neighborhood_part].blank?) || (term.split(',').length >= 2 && geo_hash[:city_part].blank?) || term.split(',').length >= 4 || term.match(/\d/).present? return true end if geo_hash[:country_part] != 'United States' if geo_hash[:city_part].blank? && geo_hash[:state_part].blank? #Currently do noting elsif !((geo_hash[:city_part].present? && term.to_ascii.downcase.include?(geo_hash[:city_part].to_ascii.downcase)) || (geo_hash[:state_part].present? && term.to_ascii.downcase.include?(geo_hash[:state_part].to_ascii.downcase))) return true end end return false end #Take LCSH subjects and make them standard. def self.LCSHize(value) #Remove ending periods ... except when an initial or etc. if value.last == '.' && value[-2].match(/[^A-Z]/) && !value[-4..-1].match('etc.') value = value.slice(0..-2) end #Fix when '- -' occurs value = value.gsub(/-\s-/,'--') #Fix for "em" dashes - two types? value = value.gsub('—','--') #Fix for "em" dashes - two types? value = value.gsub('–','--') #Fix for ' - ' combinations value = value.gsub(' - ','--') #Remove white space after and before '--' value = value.gsub(/\s+--/,'--') value = value.gsub(/--\s+/,'--') #Ensure first work is capitalized value[0] = value.first.capitalize[0] #Strip any white space value = strip_value(value) return value end def self.strip_value(value) if(value.blank?) return nil else if value.class == Float || value.class == Fixnum value = value.to_i.to_s end # Make sure it is all UTF-8 and not character encodings or HTML tags and remove any cariage returns return utf8Encode(value) end end #TODO: Better name for this. Should be part of an overall helped gem. def self.utf8Encode(value) return HTMLEntities.new.decode(ActionView::Base.full_sanitizer.sanitize(value.to_s.gsub(/\r?\n?\t/, ' ').gsub(/\r?\n/, ' ').gsub(/<br[\s]*\/>/,' '))).strip end def self.try_with_entered_names(geo_hash) geo_hash_local = geo_hash.clone if geo_hash_local[:neighborhood_part].present? orig_string_check = geo_hash_local[:standardized_term].gsub(',', ' ').squish.split(' ').select { |value| value.downcase.to_ascii == geo_hash_local[:neighborhood_part].downcase.to_ascii} geo_hash_local[:neighborhood_part] = orig_string_check.first.strip if orig_string_check.present? && orig_string_check != geo_hash_local[:neighborhood_part] return geo_hash_local end if geo_hash_local[:city_part].present? orig_string_check = geo_hash_local[:standardized_term].gsub(',', ' ').squish.split(' ').select { |value| value.downcase.to_ascii == geo_hash_local[:city_part].downcase.to_ascii} geo_hash_local[:city_part] = orig_string_check.first.strip if orig_string_check.present? return geo_hash_local end if geo_hash_local[:state_part].present? orig_string_check = geo_hash_local[:standardized_term].gsub(',', ' ').squish.split(' ').select { |value| value.downcase.to_ascii == geo_hash_local[:state_part].downcase.to_ascii} geo_hash_local[:state_part] = orig_string_check.first.strip if orig_string_check.present? return geo_hash_local end return nil end end end
joao-esteves/active_shipping
active_shipping.gemspec
lib = File.expand_path("../lib/", __FILE__) $:.unshift(lib) unless $:.include?(lib) require "active_shipping/version" Gem::Specification.new do |s| s.name = "active_shipping" s.version = ActiveShipping::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Shopify"] s.email = ["<EMAIL>"] s.homepage = "http://github.com/shopify/active_shipping" s.summary = "Simple shipping abstraction library" s.description = "Get rates and tracking info from various shipping carriers. Extracted from Shopify." s.license = "MIT" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_path = "lib" s.post_install_message = "Thanks for installing ActiveShipping! If upgrading to v2.0, please see the changelog for breaking changes: https://github.com/Shopify/active_shipping/blob/master/CHANGELOG.md." s.add_dependency("measured", ">= 2.0") s.add_dependency("activesupport", ">= 4.2", "< 8") s.add_dependency("active_utils", "~> 3.3.1") s.add_dependency("nokogiri", ">= 1.6") s.add_development_dependency("minitest") s.add_development_dependency("minitest-reporters") s.add_development_dependency("rake") s.add_development_dependency("mocha", "~> 1") s.add_development_dependency("timecop") s.add_development_dependency("business_time") s.add_development_dependency("pry") s.add_development_dependency("pry-byebug") s.add_development_dependency("vcr") s.add_development_dependency("webmock") end
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/disallow_value_matcher_spec.rb
<filename>vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/disallow_value_matcher_spec.rb require 'spec_helper' describe Shoulda::Matchers::ActiveModel::DisallowValueMatcher do it "does not allow any types" do matcher = Shoulda::Matchers::ActiveModel::DisallowValueMatcher.new("abcde") matcher.allowed_types.should == "" end context "an attribute with a format validation" do before do define_model :example, :attr => :string do validates_format_of :attr, :with => /abc/ end @model = Example.new end it "does not match if the value is allowed" do matcher = new_matcher("abcde") matcher.for(:attr) matcher.matches?(@model).should be_false end it "matches if the value is not allowed" do matcher = new_matcher("xyz") matcher.for(:attr) matcher.matches?(@model).should be_true end end context "an attribute with a format validation and a custom message" do before do define_model :example, :attr => :string do validates_format_of :attr, :with => /abc/, :message => 'good message' end @model = Example.new end it "does not match if the value and message are both correct" do matcher = new_matcher("abcde") matcher.for(:attr).with_message('good message') matcher.matches?(@model).should be_false end it "delegates its failure message to its allow matcher's negative failure message" do allow_matcher = stub_everything(:negative_failure_message => "allow matcher failure") Shoulda::Matchers::ActiveModel::AllowValueMatcher.stubs(:new).returns(allow_matcher) matcher = new_matcher("abcde") matcher.for(:attr).with_message('good message') matcher.matches?(@model) matcher.failure_message.should == "allow matcher failure" end it "matches if the message is correct but the value is not" do matcher = new_matcher("xyz") matcher.for(:attr).with_message('good message') matcher.matches?(@model).should be_true end end def new_matcher(value) matcher = Shoulda::Matchers::ActiveModel::DisallowValueMatcher.new(value) end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/unit/central_test.rb
require File.expand_path('../../test_helper', __FILE__) require 'mocha/central' require 'mocha/mock' require 'method_definer' class CentralTest < Test::Unit::TestCase include Mocha def test_should_start_with_empty_stubba_methods stubba = Central.new assert_equal [], stubba.stubba_methods end def test_should_stub_method_if_not_already_stubbed method = build_mock method.expects(:stub) stubba = Central.new stubba.stub(method) assert method.__verified__? end def test_should_not_stub_method_if_already_stubbed method = build_mock method.stubs(:matches?).returns(true) method.expects(:stub).times(0) stubba = Central.new stubba.stubba_methods = [method] stubba.stub(method) assert method.__verified__? end def test_should_record_method method = build_mock method.expects(:stub) stubba = Central.new stubba.stub(method) assert_equal [method], stubba.stubba_methods end def test_should_unstub_specified_method stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(false) method_2 = build_mock method_2.stubs(:matches?).returns(true) method_2.expects(:unstub) stubba.stubba_methods = [method_1, method_2] stubba.unstub(method_2) assert_equal [method_1], stubba.stubba_methods assert method_2.__verified__? end def test_should_not_unstub_specified_method_if_not_already_stubbed stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(false) method_2 = build_mock method_2.expects(:unstub).never stubba.stubba_methods = [method_1] stubba.unstub(method_2) assert_equal [method_1], stubba.stubba_methods assert method_2.__verified__? end def test_should_unstub_all_methods stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(true) method_1.expects(:unstub) method_2 = build_mock method_2.stubs(:matches?).returns(true) method_2.expects(:unstub) stubba.stubba_methods = [method_1, method_2] stubba.unstub_all assert_equal [], stubba.stubba_methods assert method_1.__verified__? assert method_2.__verified__? end private def build_mock Mock.new(nil) end end
beno/devise_sociable
vendor/bundle/gems/devise-1.2.1/lib/devise/version.rb
module Devise VERSION = "1.2.1".freeze end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/generators/scaffold/templates/functional_test.rb
<reponame>beno/devise_sociable require File.dirname(__FILE__) + '/../test_helper' require '<%= @controller_name %>_controller' # Re-raise errors caught by the controller. class <%= @controller_class_name %>Controller; def rescue_action(e) raise e end; end class <%= @controller_class_name %>ControllerTest < Test::Unit::TestCase fixtures :<%= table_name %> def setup @controller = <%= @controller_class_name %>Controller.new @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new end <% for action in unscaffolded_actions -%> def test_<%= action %> process :<%= action %> assert_rendered_file '<%= action %>' end <% end -%> <% unless suffix -%> def test_index process :index assert_rendered_file 'list' end <% end -%> def test_list<%= suffix %> process :list<%= suffix %> assert_rendered_file 'list<%= suffix %>' assert_template_has '<%= plural_name %>' end def test_show<%= suffix %> process :show<%= suffix %>, 'id' => 1 assert_rendered_file 'show' assert_template_has '<%= singular_name %>' assert_valid_record '<%= singular_name %>' end def test_new<%= suffix %> process :new<%= suffix %> assert_rendered_file 'new<%= suffix %>' assert_template_has '<%= singular_name %>' end def test_create num_<%= plural_name %> = <%= class_name %>.find_all.size process :create<%= suffix %>, '<%= singular_name %>' => { } assert_redirected_to :action => 'list<%= suffix %>' assert_equal num_<%= plural_name %> + 1, <%= class_name %>.find_all.size end def test_edit<%= suffix %> process :edit<%= suffix %>, 'id' => 1 assert_rendered_file 'edit<%= suffix %>' assert_template_has '<%= singular_name %>' assert_valid_record '<%= singular_name %>' end def test_update<%= suffix %> process :update<%= suffix %>, '<%= singular_name %>' => { 'id' => 1 } assert_redirected_to :action => 'show<%= suffix %>', :id => 1 end def test_destroy<%= suffix %> assert_not_nil <%= class_name %>.find(1) process :destroy, 'id' => 1 assert_redirected_to :action => 'list<%= suffix %>' assert_raise(ActiveRecord::RecordNotFound) { <%= singular_name %> = <%= class_name %>.find(1) } end end
beno/devise_sociable
vendor/bundle/gems/warden-1.0.6/spec/helpers/strategies/single.rb
<reponame>beno/devise_sociable # encoding: utf-8 Warden::Strategies.add(:single) do def authenticate! request.env['warden.spec.strategies'] ||= [] request.env['warden.spec.strategies'] << :single success!("Valid User") end def store? false end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/parser.rb
# # DO NOT MODIFY!!!! # This file is automatically generated by racc 1.4.3 # from racc grammer file "parser.y". # # # parser.rb: generated by racc (runtime embedded) # ###### racc/parser.rb unless $".index 'racc/parser.rb' $".push 'racc/parser.rb' self.class.module_eval <<'..end /home/aamine/lib/ruby/racc/parser.rb modeval..idb76f2e220d', '/home/aamine/lib/ruby/racc/parser.rb', 1 # # parser.rb # # Copyright (c) 1999-2003 <NAME> <<EMAIL>> # # 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. # # $Id: parser.rb,v 1.1.1.1 2004/10/14 11:59:58 webster132 Exp $ # 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.3' Racc_Runtime_Revision = '$Revision: 1.1.1.1 $'.split(/\s+/)[1] Racc_Runtime_Core_Version_R = '1.4.3' Racc_Runtime_Core_Revision_R = '$Revision: 1.1.1.1 $'.split(/\s+/)[1] begin require 'racc/cparse' # Racc_Runtime_Core_Version_C = (defined in extention) Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split(/\s+/)[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 self.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 if i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] ; else 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| # $stderr.puts "rd: tok=#{tok}, val=#{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 if i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] ; # $stderr.puts "01: act=#{act}" else act = action_default[@racc_state[-1]] # $stderr.puts "02: act=#{act}" # $stderr.puts "curstate=#{@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 # $ if i and i += @racc_t and i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] ; # $stderr.puts "03: act=#{act}" else # $stderr.puts "04: act=#{act}" act = action_default[@racc_state[-1]] end while act = _racc_evalact(act, arg) end end end } end ### ### common ### def _racc_evalact( act, arg ) # $stderr.puts "ea: act=#{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 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 RuntimeError, '[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 < 2 @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 RuntimeError, "[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 RuntimeError, "[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 /home/aamine/lib/ruby/racc/parser.rb modeval..idb76f2e220d end # end of racc/parser.rb # # parser.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # require 'tmail/scanner' require 'tmail/utils' module TMail class Parser < Racc::Parser module_eval <<'..end parser.y modeval..id43721faf1c', 'parser.y', 331 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..id43721faf1c ##### racc 1.4.3 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, 1, 82, :_reduce_none, 1, 82, :_reduce_none, 1, 44, :_reduce_99, 3, 45, :_reduce_100, 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 = 110 racc_shift_n = 168 racc_action_table = [ -70, -69, 23, 25, 146, 147, 29, 31, 105, 106, 16, 17, 20, 22, 136, 27, -70, -69, 32, 101, -70, -69, 154, 100, 113, 115, -70, -69, -70, 109, 75, 23, 25, 101, 155, 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, 148, 32, 23, 25, 120, 149, 29, 31, 152, 153, 16, 17, 20, 22, 42, 27, 157, 159, 32, 23, 25, 120, 40, 29, 31, 15, 164, 16, 17, 20, 22, 40, 27, 23, 25, 32, 68, 29, 31, 166, 167, 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, 152, 152, 3, 62, 152, 152, 60, 56, 152, 152, 152, 152, 51, 152, 52, 52, 152, 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, 148, 151, 90, 127, 127, 127, 4, 127, 127, 1, 157, 127, 127, 127, 127, 159, 127, 26, 26, 127, 26, 26, 26, 163, 164, 26, 26, 26, 26, nil, 26, 27, 27, 26, nil, 27, 27, 27, nil, 27, 27, 27, 27, nil, 155, 155, nil, 27, 155, 155, nil, nil, 155, 155, 155, 155, nil, 122, 122, nil, 155, 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, nil, 160, nil, nil, 149, 31, nil, nil, 204, nil, 167, nil, 174, nil, nil, nil, 169, 184, nil, nil, nil ] racc_action_default = [ -110, -110, -110, -110, -14, -110, -20, -110, -110, -110, -110, -110, -110, -110, -10, -95, -106, -107, -77, -44, -108, -11, -109, -79, -43, -103, -110, -110, -60, -104, -55, -105, -78, -68, -54, -71, -45, -12, -110, -1, -110, -110, -110, -2, -110, -22, -51, -48, -50, -3, -40, -41, -110, -46, -4, -86, -5, -88, -6, -90, -110, -7, -95, -8, -9, -99, -101, -61, -59, -56, -69, -110, -110, -110, -110, -75, -110, -110, -57, -15, -110, 168, -73, -80, -82, -21, -24, -81, -110, -27, -110, -83, -47, -89, -110, -91, -110, -101, -110, -100, -102, -75, -58, -52, -110, -110, -64, -63, -65, -76, -72, -67, -110, -110, -110, -26, -23, -110, -29, -49, -84, -42, -87, -92, -94, -95, -110, -110, -62, -110, -110, -25, -74, -28, -31, -101, -110, -53, -66, -110, -110, -34, -110, -110, -93, -96, -98, -97, -110, -18, -13, -38, -110, -30, -33, -110, -32, -16, -19, -14, -35, -36, -37, -110, -110, -39, -85, -17 ] racc_goto_table = [ 39, 67, 70, 73, 24, 37, 69, 66, 36, 38, 57, 59, 55, 67, 108, 83, 90, 111, 69, 99, 85, 49, 53, 76, 158, 134, 141, 70, 73, 151, 118, 89, 45, 156, 160, 150, 140, 21, 14, 19, 119, 102, 64, 63, 61, 83, 70, 104, 83, 58, 124, 132, 56, 131, 97, 54, 93, 43, 5, 83, 95, 145, 76, nil, 116, 76, nil, nil, 127, 138, 103, nil, nil, nil, 38, nil, nil, 110, nil, nil, nil, nil, nil, nil, 83, 83, nil, nil, 144, nil, nil, nil, nil, nil, nil, 57, 121, 122, nil, nil, 83, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 135, nil, nil, nil, nil, nil, 93, nil, nil, nil, 70, 162, 137, 70, 163, 161, 38, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 165 ] racc_goto_check = [ 2, 37, 37, 29, 13, 13, 28, 46, 31, 36, 41, 41, 45, 37, 25, 44, 32, 25, 28, 47, 24, 4, 4, 42, 23, 20, 21, 37, 29, 22, 19, 18, 17, 26, 27, 16, 15, 12, 11, 33, 34, 35, 10, 9, 8, 44, 37, 29, 44, 7, 47, 43, 6, 25, 46, 5, 41, 3, 1, 44, 41, 48, 42, nil, 24, 42, nil, nil, 32, 25, 13, nil, nil, nil, 36, nil, nil, 41, nil, nil, nil, nil, nil, nil, 44, 44, nil, nil, 47, nil, nil, nil, nil, nil, nil, 41, 31, 45, nil, nil, 44, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 46, nil, nil, nil, nil, nil, 41, nil, nil, nil, 37, 29, 13, 37, 29, 28, 36, 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, 58, -4, 51, 14, 47, 43, 39, 33, 31, 29, 37, 35, 2, nil, -94, -105, 26, -14, -59, -93, -108, -112, -127, -24, -60, -110, -118, -20, -24, nil, 6, -34, 37, -50, -27, 6, -25, nil, nil, nil, 1, -5, -63, -29, 3, -8, -47, -75 ] 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, 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', 'value'] 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', 33 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', 42 def _reduce_16( val, _values) (val[0].to_i * 60 * 60) + (val[2].to_i * 60) end .,., module_eval <<'.,.,', 'parser.y', 47 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', 54 def _reduce_18( val, _values) timezone_string_to_unixtime(val[0]) end .,., module_eval <<'.,.,', 'parser.y', 59 def _reduce_19( val, _values) val end .,., # reduce 20 omitted module_eval <<'.,.,', 'parser.y', 65 def _reduce_21( val, _values) val[1] end .,., # reduce 22 omitted module_eval <<'.,.,', 'parser.y', 71 def _reduce_23( val, _values) val[1] end .,., module_eval <<'.,.,', 'parser.y', 77 def _reduce_24( val, _values) join_domain(val[0]) end .,., module_eval <<'.,.,', 'parser.y', 81 def _reduce_25( val, _values) join_domain(val[2]) end .,., module_eval <<'.,.,', 'parser.y', 85 def _reduce_26( val, _values) join_domain(val[0]) end .,., # reduce 27 omitted module_eval <<'.,.,', 'parser.y', 91 def _reduce_28( val, _values) val[1] end .,., module_eval <<'.,.,', 'parser.y', 96 def _reduce_29( val, _values) [] end .,., module_eval <<'.,.,', 'parser.y', 100 def _reduce_30( val, _values) val[0].push val[2] val[0] end .,., # reduce 31 omitted module_eval <<'.,.,', 'parser.y', 107 def _reduce_32( val, _values) val[1] end .,., module_eval <<'.,.,', 'parser.y', 111 def _reduce_33( val, _values) val[1] end .,., # reduce 34 omitted module_eval <<'.,.,', 'parser.y', 117 def _reduce_35( val, _values) val[1] end .,., module_eval <<'.,.,', 'parser.y', 123 def _reduce_36( val, _values) val[0].spec end .,., module_eval <<'.,.,', 'parser.y', 127 def _reduce_37( val, _values) val[0].spec end .,., # reduce 38 omitted module_eval <<'.,.,', 'parser.y', 134 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', 148 def _reduce_48( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 149 def _reduce_49( val, _values) val[0].push val[2]; val[0] end .,., # reduce 50 omitted # reduce 51 omitted module_eval <<'.,.,', 'parser.y', 156 def _reduce_52( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 160 def _reduce_53( val, _values) val[0].push val[2] val[0] end .,., # reduce 54 omitted # reduce 55 omitted module_eval <<'.,.,', 'parser.y', 168 def _reduce_56( val, _values) val[1].phrase = Decoder.decode(val[0]) val[1] end .,., # reduce 57 omitted module_eval <<'.,.,', 'parser.y', 176 def _reduce_58( val, _values) AddressGroup.new(val[0], val[2]) end .,., module_eval <<'.,.,', 'parser.y', 178 def _reduce_59( val, _values) AddressGroup.new(val[0], []) end .,., module_eval <<'.,.,', 'parser.y', 181 def _reduce_60( val, _values) val[0].join('.') end .,., module_eval <<'.,.,', 'parser.y', 182 def _reduce_61( val, _values) val[0] << ' ' << val[1].join('.') end .,., module_eval <<'.,.,', 'parser.y', 186 def _reduce_62( val, _values) val[2].routes.replace val[1] val[2] end .,., module_eval <<'.,.,', 'parser.y', 191 def _reduce_63( val, _values) val[1] end .,., # reduce 64 omitted module_eval <<'.,.,', 'parser.y', 196 def _reduce_65( val, _values) [ val[1].join('.') ] end .,., module_eval <<'.,.,', 'parser.y', 197 def _reduce_66( val, _values) val[0].push val[3].join('.'); val[0] end .,., module_eval <<'.,.,', 'parser.y', 199 def _reduce_67( val, _values) Address.new( val[0], val[2] ) end .,., module_eval <<'.,.,', 'parser.y', 200 def _reduce_68( val, _values) Address.new( val[0], nil ) end .,., # reduce 69 omitted module_eval <<'.,.,', 'parser.y', 203 def _reduce_70( val, _values) val[0].push ''; val[0] end .,., module_eval <<'.,.,', 'parser.y', 206 def _reduce_71( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 209 def _reduce_72( val, _values) val[1].times do val[0].push '' end val[0].push val[2] val[0] end .,., module_eval <<'.,.,', 'parser.y', 217 def _reduce_73( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 220 def _reduce_74( val, _values) val[1].times do val[0].push '' end val[0].push val[2] val[0] end .,., module_eval <<'.,.,', 'parser.y', 227 def _reduce_75( val, _values) 0 end .,., module_eval <<'.,.,', 'parser.y', 228 def _reduce_76( val, _values) 1 end .,., # reduce 77 omitted # reduce 78 omitted # reduce 79 omitted # reduce 80 omitted # reduce 81 omitted # reduce 82 omitted # reduce 83 omitted # reduce 84 omitted module_eval <<'.,.,', 'parser.y', 243 def _reduce_85( val, _values) val[1] = val[1].spec val.join('') end .,., module_eval <<'.,.,', 'parser.y', 247 def _reduce_86( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 248 def _reduce_87( val, _values) val[0].push val[2]; val[0] end .,., # reduce 88 omitted module_eval <<'.,.,', 'parser.y', 251 def _reduce_89( val, _values) val[0] << ' ' << val[1] end .,., module_eval <<'.,.,', 'parser.y', 255 def _reduce_90( val, _values) val.push nil val end .,., module_eval <<'.,.,', 'parser.y', 260 def _reduce_91( val, _values) val end .,., module_eval <<'.,.,', 'parser.y', 265 def _reduce_92( val, _values) [ val[0].to_i, val[2].to_i ] end .,., module_eval <<'.,.,', 'parser.y', 270 def _reduce_93( val, _values) [ val[0].downcase, val[2].downcase, decode_params(val[3]) ] end .,., module_eval <<'.,.,', 'parser.y', 274 def _reduce_94( val, _values) [ val[0].downcase, nil, decode_params(val[1]) ] end .,., module_eval <<'.,.,', 'parser.y', 279 def _reduce_95( val, _values) {} end .,., module_eval <<'.,.,', 'parser.y', 283 def _reduce_96( val, _values) val[0][ val[2].downcase ] = val[4] val[0] end .,., # reduce 97 omitted # reduce 98 omitted module_eval <<'.,.,', 'parser.y', 292 def _reduce_99( val, _values) val[0].downcase end .,., module_eval <<'.,.,', 'parser.y', 297 def _reduce_100( val, _values) [ val[0].downcase, decode_params(val[1]) ] end .,., # reduce 101 omitted # reduce 102 omitted # reduce 103 omitted # reduce 104 omitted # reduce 105 omitted # reduce 106 omitted # reduce 107 omitted # reduce 108 omitted # reduce 109 omitted def _reduce_none( val, _values) val[0] end end # class Parser end # module TMail
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/test/mail_service_test.rb
$:.unshift(File.dirname(__FILE__) + "/../lib/") require 'test/unit' require 'action_mailer' class TestMailer < ActionMailer::Base def signed_up(recipient) @recipients = recipient @subject = "[Signed up] Welcome #{recipient}" @from = "<EMAIL>" @sent_on = Time.local(2004, 12, 12) @body["recipient"] = recipient end def cancelled_account(recipient) @recipients = recipient @subject = "[Cancelled] Goodbye #{recipient}" @from = "<EMAIL>" @sent_on = Time.local(2004, 12, 12) @body = "Goodbye, Mr. #{recipient}" end def cc_bcc(recipient) @recipients = recipient @subject = "testing bcc/cc" @from = "<EMAIL>" @sent_on = Time.local 2004, 12, 12 @cc = "<EMAIL>" @bcc = "<EMAIL>" @body = "Nothing to see here." end end TestMailer.template_root = File.dirname(__FILE__) + "/fixtures" class ActionMailerTest < Test::Unit::TestCase def setup ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] @recipient = 'test@localhost' end def test_signed_up expected = TMail::Mail.new expected.to = @recipient expected.subject = "[Signed up] Welcome #{@recipient}" expected.body = "Hello there, \n\nMr. #{@recipient}" expected.from = "<EMAIL>" expected.date = Time.local(2004, 12, 12) 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_cancelled_account expected = TMail::Mail.new expected.to = @recipient expected.subject = "[Cancelled] Goodbye #{@recipient}" expected.body = "Goodbye, Mr. #{@recipient}" expected.from = "<EMAIL>" 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 = TMail::Mail.new expected.to = @recipient expected.subject = "testing bcc/cc" expected.body = "Nothing to see here." expected.from = "<EMAIL>" expected.cc = "<EMAIL>" expected.bcc = "<EMAIL>" 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_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 end
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/lib/shoulda/matchers/version.rb
module Shoulda module Matchers VERSION = '1.4.2'.freeze end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/lib/mocha/thrower.rb
<gh_stars>1-10 module Mocha # :nodoc: class Thrower # :nodoc: def initialize(tag, object = nil) @tag, @object = tag, object end def evaluate throw @tag, @object end end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/lib/rails_generator.rb
<filename>vendor/bundle/gems/rails-0.9.5/lib/rails_generator.rb require 'fileutils' module Rails module Generator class GeneratorError < StandardError; end class UsageError < GeneratorError; end CONTRIB_ROOT = "#{RAILS_ROOT}/script/generators" BUILTIN_ROOT = "#{File.dirname(__FILE__)}/../generators" DEFAULT_SEARCH_PATHS = [CONTRIB_ROOT, BUILTIN_ROOT] class << self def instance(name, args = [], search_paths = DEFAULT_SEARCH_PATHS) # RAILS_ROOT constant must be set. unless Object.const_get(:RAILS_ROOT) raise GeneratorError, "RAILS_ROOT must be set. Did you require 'config/environment'?" end # Force canonical name. name = Inflector.underscore(name.downcase) # Search for filesystem path to requested generator. unless path = find_generator_path(name, search_paths) raise GeneratorError, "#{name} generator not found." end # Check for templates directory. template_root = "#{path}/templates" unless File.directory?(template_root) raise GeneratorError, "missing template directory #{template_root}" end # Require class file according to naming convention. require "#{path}/#{name}_generator.rb" # Find class according to naming convention. Allow Nesting::In::Modules. class_name = Inflector.classify("#{name}_generator") unless klass = find_generator_class(name) raise GeneratorError, "no #{class_name} class defined in #{path}/#{name}_generator.rb" end # Instantiate and return generator. klass.new(template_root, RAILS_ROOT, search_paths, args) end def builtin_generators generators([BUILTIN_ROOT]) end def contrib_generators generators([CONTRIB_ROOT]) end def generators(search_paths) generator_paths(search_paths).keys.uniq.sort end # Find all generator paths. def generator_paths(search_paths) @paths ||= {} unless @paths[search_paths] paths = Hash.new { |h,k| h[k] = [] } search_paths.each do |path| Dir["#{path}/[a-z]*"].each do |dir| paths[File.basename(dir)] << dir if File.directory?(dir) end end @paths[search_paths] = paths end @paths[search_paths] end def find_generator_path(name, search_paths) generator_paths(search_paths)[name].first end # Find all generator classes. def generator_classes classes = Hash.new { |h,k| h[k] = [] } class_re = /([^:]+)Generator$/ ObjectSpace.each_object(Class) do |object| if md = class_re.match(object.name) and object < Rails::Generator::Base classes[Inflector.underscore(md.captures.first)] << object end end classes end def find_generator_class(name) generator_classes[name].first end end # Talk about generators. class Base attr_reader :template_root, :destination_root, :args, :options, :class_name, :singular_name, :plural_name alias_method :file_name, :singular_name alias_method :table_name, :plural_name def self.generator_name Inflector.underscore(name.gsub('Generator', '')) end def initialize(template_root, destination_root, search_paths, args) @template_root, @destination_root = template_root, destination_root usage if args.empty? @search_paths, @original_args = search_paths, args.dup @class_name, @singular_name, @plural_name = inflect_names(args.shift) @options = extract_options!(args) @args = args end # Checks whether the class name that was assigned to this generator # would cause a collision with a Class, Module or other constant # that is already used up by Ruby or RubyOnRails. def collision_with_builtin? builtin = Object.const_get(full_class_name) rescue nil type = case builtin when Class: "Class" when Module: "Module" else "Constant" end if builtin then "Sorry, you can't have a #{self.class.generator_name} named " + "'#{full_class_name}' because Ruby or Rails already has a #{type} with that name.\n" + "Please rerun the generator with a different name." end end # Returns the complete name that the resulting Class would have. # Used in collision_with_builtin(). The default guess is that it is # the same as class_name. Override this in your generator in case # it is wrong. def full_class_name class_name end protected # Look up another generator with the same arguments. def generator(name) Rails::Generator.instance(name, @original_args, @search_paths) end # Generate a file for a Rails application using an ERuby template. # Looks up and evalutes a template by name and writes the result # to a file relative to +destination_root+. The template # is evaluated in the context of the optional eval_binding argument. # # The ERB template uses explicit trim mode to best control the # proliferation of whitespace in generated code. <%- trims leading # whitespace; -%> trims trailing whitespace including one newline. def template(template_name, destination_path, eval_binding = nil) # Determine full paths for source and destination files. template_path = find_template_path(template_name) destination_path = File.join(destination_root, destination_path) # Create destination directories. FileUtils.mkdir_p(File.dirname(destination_path)) # Render template and write result. eval_binding ||= binding contents = ERB.new(File.read(template_path), nil, '-').result(eval_binding) File.open(destination_path, 'w') { |file| file.write(contents) } end def usage raise UsageError.new, File.read(usage_path) end private def find_template_path(template_name) name, path = template_name.split('/', 2) if path.nil? File.join(template_root, name) elsif generator_path = Rails::Generator.find_generator_path(name, @search_paths) File.join(generator_path, 'templates', path) end end def inflect_names(name) camel = Inflector.camelize(Inflector.underscore(name)) under = Inflector.underscore(camel) plural = Inflector.pluralize(under) [camel, under, plural] end def extract_options!(args) if args.last.is_a?(Hash) then args.pop else {} end end def usage_path "#{template_root}/../USAGE" end end end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/acceptance/stub_class_method_defined_on_active_record_association_proxy_test.rb
<reponame>beno/devise_sociable require File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha' class StubClassMethodDefinedOnActiveRecordAssociationProxyTest < Test::Unit::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_be_able_to_stub_method_if_ruby18_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def public_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def public_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def protected_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def protected_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def private_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def private_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end end
beno/devise_sociable
vendor/bundle/gems/devise-1.5.4/test/models/authenticatable_test.rb
<filename>vendor/bundle/gems/devise-1.5.4/test/models/authenticatable_test.rb require 'test_helper' class AuthenticatableTest < ActiveSupport::TestCase test 'find_first_by_auth_conditions allows custom filtering parameters' do user = User.create!(email: "<EMAIL>", password: "<PASSWORD>") assert_equal User.find_first_by_auth_conditions({ email: "<EMAIL>" }), user assert_equal User.find_first_by_auth_conditions({ email: "<EMAIL>" }, id: user.id + 1), nil end end
beno/devise_sociable
vendor/bundle/gems/devise-1.2.1/lib/devise/rails.rb
require 'devise/rails/routes' require 'devise/rails/warden_compat' module Devise class Engine < ::Rails::Engine config.devise = Devise # Initialize Warden and copy its configurations. config.app_middleware.use Warden::Manager do |config| Devise.warden_config = config end # Force routes to be loaded if we are doing any eager load. config.before_eager_load { |app| app.reload_routes! } initializer "devise.url_helpers" do Devise.include_helpers(Devise::Controllers) end initializer "devise.navigationals" do formats = Devise.navigational_formats if formats.include?(:"*/*") && formats.exclude?("*/*") puts "[DEVISE] We see the symbol :\"*/*\" in the navigational formats in your initializer " \ "but not the string \"*/*\". Due to changes in latest Rails, please include the latter." end end initializer "devise.omniauth" do |app| Devise.omniauth_configs.each do |provider, config| app.middleware.use config.strategy_class, *config.args do |strategy| config.strategy = strategy end end if Devise.omniauth_configs.any? Devise.include_helpers(Devise::OmniAuth) end end initializer "devise.encryptor_check" do case Devise.encryptor when :bcrypt puts "[DEVISE] From version 1.2, there is no need to set your encryptor to bcrypt " \ "since encryptors are only enabled if you include :encryptable in your models. " \ "To update your app, please:\n\n" \ "1) Remove config.encryptor from your initializer;\n" \ "2) Add t.encryptable to your old migrations;\n" \ "3) [Optional] Remove password_salt in a new recent migration. Bcrypt does not require it anymore.\n" when nil # Nothing to say else puts "[DEVISE] You are using #{Devise.encryptor} as encryptor. From version 1.2, " \ "you need to explicitly add encryptable as dependency. To update your app, please:\n\n" \ "1) Remove config.encryptor from your initializer;\n" \ "2) Add t.encryptable to your old migrations;\n" \ "3) Add `devise :encryptable, :encryptor => :#{Devise.encryptor}` to your models.\n" end end end end
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/test/unit/have_received_test.rb
<reponame>beno/devise_sociable require File.join(File.dirname(__FILE__), "..", "test_helper") require 'test_runner' require 'bourne/api' require 'bourne/mockery' require 'mocha/object' require 'matcher_helpers' module HaveReceivedTestMethods include Mocha def teardown Mockery.reset_instance end def test_passes_if_invocation_exists method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, []) assert_passes do assert_matcher_accepts have_received(method), mock end end def test_fails_if_invocation_doesnt_exist method = :a_method mock = new_mock('a mock') assert_fails do assert_matcher_accepts have_received(method), mock end end def test_fails_if_invocation_exists_with_different_arguments method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, [2, 1]) assert_fails do assert_matcher_accepts have_received(method).with(1, 2), mock end end def test_passes_if_invocation_exists_with_wildcard_arguments method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_matcher_accepts have_received(method).with(is_a(String)), mock end end def test_passes_if_invocation_exists_with_exact_arguments method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_matcher_accepts have_received(method).with('hello'), mock end end def test_fails_if_invocation_exists_only_on_other_mock method = :a_method mock = new_mock('a mock') other = 'another mock' Mockery.instance.invocation(other, method, ['hello']) assert_fails do assert_matcher_accepts have_received(method), mock end end def test_passes_if_invocation_exists_for_impersonating_mock method = :a_method object = Object.new mock = new_mock('a mock') class << object attr_accessor :mocha end object.mocha = mock Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_matcher_accepts have_received(method).with('hello'), object end end def test_passes_if_invocation_count_correct method = :a_method mock = new_mock('a mock') 2.times { Mockery.instance.invocation(mock, method, []) } assert_passes do assert_matcher_accepts have_received(method).twice, mock end end def test_fails_if_invocation_count_incorrect method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, []) assert_fails do assert_matcher_accepts have_received(method).twice, mock end end def test_fails_if_invocation_count_too_low method = :a_method mock = new_mock('a mock') Mockery.instance.invocation(mock, method, []) assert_fails do assert_matcher_accepts have_received(method).twice, mock end end def test_fails_if_invocation_count_too_high method = :a_method mock = new_mock('a mock') 2.times { Mockery.instance.invocation(mock, method, []) } assert_fails do assert_matcher_accepts have_received(method).once, mock end end def assert_passes(&block) assert ! fails?(&block) end def assert_fails(&block) assert fails?(&block) end def fails? begin yield false rescue FailedAssertion true end end end class PartialHaveReceivedTest < Test::Unit::TestCase include TestRunner include Mocha::API include HaveReceivedTestMethods class FakeMock def initialize(name) @name = name end def inspect @name end def mocha self end end def new_mock(*args) FakeMock.new(*args) end end class PureHaveReceivedTest < Test::Unit::TestCase include TestRunner include Mocha::API include HaveReceivedTestMethods class FakeMock def initialize(name) @name = name end def inspect @name end def mocha self end end def new_mock(*args) Mocha::Mock.new(*args) end end
beno/devise_sociable
vendor/bundle/gems/devise-1.5.4/test/path_checker_test.rb
require 'test_helper' class PathCheckerTest < ActiveSupport::TestCase test 'check if sign out path matches' do path_checker = Devise::PathChecker.new({"PATH_INFO" => "/users/sign_out"}, :user) assert path_checker.signing_out? path_checker = Devise::PathChecker.new({"PATH_INFO" => "/users/sign_in"}, :user) assert_not path_checker.signing_out? end test 'considers script name' do path_checker = Devise::PathChecker.new({"SCRIPT_NAME" => "/users", "PATH_INFO" => "/sign_out"}, :user) assert path_checker.signing_out? end test 'ignores invalid routes' do path_checker = Devise::PathChecker.new({"PATH_INFO" => "/users/sign_in"}, :omg) assert_not path_checker.signing_out? end end
beno/devise_sociable
lib/devise_sociable.rb
<filename>lib/devise_sociable.rb unless defined?(Devise) require 'devise' end require 'devise_sociable' Devise.add_module :sociable, :model => 'devise_sociable/model' module DeviseSociable end require 'devise_sociable/rails'
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/generators/model/model_generator.rb
require 'rails_generator' class ModelGenerator < Rails::Generator::Base def generate # Model class, unit test, and fixtures. template "model.rb", "app/models/#{file_name}.rb" template "unit_test.rb", "test/unit/#{file_name}_test.rb" template "fixtures.yml", "test/fixtures/#{table_name}.yml" end end
beno/devise_sociable
vendor/bundle/gems/shoulda-context-1.0.2/lib/shoulda/context/version.rb
<filename>vendor/bundle/gems/shoulda-context-1.0.2/lib/shoulda/context/version.rb module Shoulda module Context VERSION = '1.0.2'.freeze end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/environments/shared.rb
RAILS_ROOT = File.dirname(__FILE__) + "/../" RAILS_ENV = ENV['RAILS_ENV'] || 'development' # Mocks first. ADDITIONAL_LOAD_PATHS = ["#{RAILS_ROOT}/test/mocks/#{RAILS_ENV}"] # Then model subdirectories. ADDITIONAL_LOAD_PATHS.concat(Dir["#{RAILS_ROOT}/app/models/[_a-z]*"]) # Followed by the standard includes. ADDITIONAL_LOAD_PATHS.concat %w( app app/models app/controllers app/helpers config lib vendor vendor/railties vendor/railties/lib vendor/activerecord/lib vendor/actionpack/lib vendor/actionmailer/lib ).map { |dir| "#{RAILS_ROOT}/#{dir}" } # Prepend to $LOAD_PATH ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } # Require Rails libraries. require 'active_record' require 'action_controller' require 'action_mailer' # Environment-specific configuration. require_dependency "environments/#{RAILS_ENV}" ActiveRecord::Base.configurations = YAML::load(File.open("#{RAILS_ROOT}/config/database.yml")) ActiveRecord::Base.establish_connection # Configure defaults if the included environment did not. begin RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log") rescue StandardError RAILS_DEFAULT_LOGGER = Logger.new(STDERR) RAILS_DEFAULT_LOGGER.level = Logger::WARN RAILS_DEFAULT_LOGGER.warn( "Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) end [ActiveRecord::Base, ActionController::Base, ActionMailer::Base].each do |klass| klass.logger ||= RAILS_DEFAULT_LOGGER end [ActionController::Base, ActionMailer::Base].each do |klass| klass.template_root ||= "#{RAILS_ROOT}/app/views/" end # Include your app's configuration here:
beno/devise_sociable
vendor/bundle/gems/warden-1.2.1/lib/warden/version.rb
<reponame>beno/devise_sociable<filename>vendor/bundle/gems/warden-1.2.1/lib/warden/version.rb # encoding: utf-8 module Warden VERSION = "1.2.1".freeze end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/acceptance/stub_class_method_defined_on_superclass_test.rb
require File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha' class StubClassMethodDefinedOnSuperclassTest < Test::Unit::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end public :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.my_class_method end assert_passed(test_result) end assert_equal :original_return_value, klass.my_class_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end protected :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end private :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/acceptance/throw_test.rb
<gh_stars>1-10 require File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha' class ThrowTest < Test::Unit::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_throw_tag test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag) assert_throws(:tag) { foo.bar } end assert_passed(test_result) end def test_should_throw_with_return_value test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag, 'return-value') return_value = catch(:tag) { foo.bar } assert_equal 'return-value', return_value end assert_passed(test_result) end def test_should_throw_two_different_tags test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag_one).then.throws(:tag_two) assert_throws(:tag_one) { foo.bar } assert_throws(:tag_two) { foo.bar } end assert_passed(test_result) end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/stringio.rb
# # stringio.rb # # Copyright (c) 1999-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # # Id: stringio.rb,v 1.10 2003/04/27 22:02:14 aamine Exp # 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'},#{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
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/lib/shoulda/matchers/active_model/only_integer_matcher.rb
module Shoulda # :nodoc: module Matchers module ActiveModel # :nodoc: class OnlyIntegerMatcher # :nodoc: NON_INTEGER_VALUE = 0.1 def initialize(attribute) @attribute = attribute @disallow_value_matcher = DisallowValueMatcher.new(NON_INTEGER_VALUE). for(attribute). with_message(:not_an_integer) end def matches?(subject) @disallow_value_matcher.matches?(subject) end def with_message(message) @disallow_value_matcher.with_message(message) self end def allowed_types "integer" end def failure_message @disallow_value_matcher.failure_message end end end end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/mail_helper.rb
<reponame>beno/devise_sociable require 'action_mailer/vendor/text/format' module MailHelper#:nodoc: 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
beno/devise_sociable
lib/devise_sociable/rails.rb
require 'devise_sociable' module DeviseSociable class Engine < ::Rails::Engine end end
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/lib/bourne/mock.rb
<filename>vendor/bundle/gems/bourne-1.1.2/lib/bourne/mock.rb require 'mocha/mock' require 'bourne/expectation' module Mocha # :nodoc: # Overwrites #method_missing on Mocha::Mock so pass arguments to # Mocha::Expectation#invoke so that an Invocation can be created. class Mock # :nodoc: def method_missing(symbol, *arguments, &block) if @responder and not @responder.respond_to?(symbol) raise NoMethodError, "undefined method `#{symbol}' for #{self.mocha_inspect} which responds like #{@responder.mocha_inspect}" end if matching_expectation_allowing_invocation = @expectations.match_allowing_invocation(symbol, *arguments) matching_expectation_allowing_invocation.invoke(arguments, &block) else if (matching_expectation = @expectations.match(symbol, *arguments)) || (!matching_expectation && !@everything_stubbed) matching_expectation.invoke(arguments, &block) if matching_expectation message = UnexpectedInvocation.new(self, symbol, *arguments).to_s message << @mockery.mocha_inspect raise ExpectationError.new(message, caller) else target = if self.respond_to? :mocha self.mocha else mocha end Mockery.instance.invocation(target, symbol, arguments) nil end end end end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/helpers/test_helper.rb
ENV["RAILS_ENV"] = "test" require File.dirname(__FILE__) + "/../config/environment" require 'application' require 'test/unit' require 'active_record/fixtures' require 'action_controller/test_process' require 'breakpoint' def create_fixtures(*table_names) Fixtures.create_fixtures(File.dirname(__FILE__) + "/fixtures", table_names) end Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/"
beno/devise_sociable
lib/generators/devise_sociable/templates/migration.rb
<filename>lib/generators/devise_sociable/templates/migration.rb class DeviseSociable<%= table_name.camelize.singularize %> < ActiveRecord::Migration def self.up add_column :<%= table_name %>, :last_request_at, :datetime add_column :<%= table_name %>, :last_sign_out_at, :datetime end def self.down remove_column :<%= table_name %>, :last_request_at remove_column :<%= table_name %>, :last_sign_out_at end end
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/lib/bourne/expectation.rb
<filename>vendor/bundle/gems/bourne-1.1.2/lib/bourne/expectation.rb require 'mocha/expectation' module Mocha # :nodoc: # Extends Mocha::Expectation to record the full arguments and count whenver a # stubbed or mocked method is invoked. class Expectation # :nodoc: attr_accessor :invocation_count def invoke_with_args(args, &block) Mockery.instance.invocation(@mock, method_name, args) invoke_without_args(&block) end alias_method :invoke_without_args, :invoke alias_method :invoke, :invoke_with_args private def method_name @method_matcher.expected_method_name end end end
beno/devise_sociable
test/support/helpers.rb
<filename>test/support/helpers.rb class ActiveSupport::TestCase def setup_rails(store) config = Struct.new(:session_store).new(store) app = Struct.new(:config).new(config) Rails.stubs(:application).returns(app) end def session_data(user, last_access) { "warden.user.user.session"=>{"last_request_at"=>last_access}, "warden.user.user.key"=>["User", [user.id], ""], } end def valid_attributes(attributes={}) {session_id:(1000*rand).to_i, data:''}.update(attributes) end def create_session(user, last_access) session = session_store::Session.create!(valid_attributes(data: session_data(user, last_access))) session.update_attribute(:updated_at, last_access) end def create_anonymous_session session_store::Session.create!(valid_attributes) end def create_user(atts = {}) User.create!({email: "<EMAIL>#{(rand*100).<EMAIL>"}.update(atts)) end def session_store Rails.application.config.session_store end end
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/validate_numericality_of_matcher_spec.rb
<reponame>beno/devise_sociable require 'spec_helper' describe Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher do it "should state in its description that it allows only numeric values" do matcher = Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher.new(:attr) matcher.description.should == "only allow numeric values for attr" end context "given a numeric attribute" do before do define_model :example, :attr => :string do validates_numericality_of :attr end @model = Example.new end it "should only allow numeric values for that attribute" do matcher = new_matcher(:attr) matcher.matches?(@model).should be_true end it "should not override the default message with a blank" do matcher = new_matcher(:attr) matcher.with_message(nil) matcher.matches?(@model).should be_true end context "when asked to enforce integer values for that attribute" do it "should not match" do matcher = new_matcher(:attr) matcher.only_integer matcher.matches?(@model).should be_false end it "should fail with the ActiveRecord :not_an_integer message" do matcher = new_matcher(:attr) matcher.only_integer matcher.matches?(@model) matcher.failure_message.should include 'Expected errors to include "must be an integer"' end end end context "given a numeric attribute which must be integer" do before do define_model :example, :attr => :string do validates_numericality_of :attr, { :only_integer => true } end @model = Example.new end it "allows integer values for that attribute" do matcher = new_matcher(:attr) matcher.only_integer matcher.matches?(@model).should be_true end it "does not allow non-integer values for that attribute" do matcher = new_matcher(:attr) matcher.only_integer matcher.matches?(@model).should be_true end it "should state in its description that it allows only integer values" do matcher = new_matcher(:attr) matcher.only_integer matcher.description.should == "only allow numeric, integer values for attr" end end context "given a numeric attribute with a custom validation message" do before do define_model :example, :attr => :string do validates_numericality_of :attr, :message => 'custom' end @model = Example.new end it "should only allow numeric values for that attribute with that message" do matcher = new_matcher(:attr) matcher.with_message(/custom/) matcher.matches?(@model).should be_true end it "should not allow numeric values for that attribute with another message" do matcher = new_matcher(:attr) matcher.with_message(/wrong/) matcher.matches?(@model).should be_false end end context "given a non-numeric attribute" do before do @model = define_model(:example, :attr => :string).new end it "should not only allow numeric values for that attribute" do matcher = new_matcher(:attr) matcher.matches?(@model).should be_false end it "should fail with the ActiveRecord :not_a_number message" do matcher = new_matcher(:attr) matcher.matches?(@model) matcher.failure_message.should include 'Expected errors to include "is not a number"' end end def new_matcher(attr) Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher.new(attr) end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/environments/development.rb
<gh_stars>1-10 Dependencies.mechanism = :load ActionController::Base.consider_all_requests_local = true ActionController::Base.perform_caching = false BREAKPOINT_SERVER_PORT = 42531
beno/devise_sociable
vendor/bundle/specifications/rails-0.9.5.gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "rails" s.version = "0.9.5" s.required_rubygems_version = nil if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.cert_chain = nil s.date = "2005-01-25" s.description = "Rails is a framework for building web-application using CGI, FCGI, mod_ruby, or WEBrick on top of either MySQL, PostgreSQL, or SQLite with eRuby-based templates." s.email = "<EMAIL>" s.executables = ["rails"] s.files = ["bin/rails"] s.homepage = "http://www.rubyonrails.org" s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new("> 0.0.0") s.rubyforge_project = "rails" s.rubygems_version = "1.8.23" s.summary = "Web-application framework with template engine, control-flow layer, and ORM." if s.respond_to? :specification_version then s.specification_version = 1 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rake>, [">= 0.4.15"]) s.add_runtime_dependency(%q<activerecord>, [">= 1.6.0"]) s.add_runtime_dependency(%q<actionpack>, [">= 1.4.0"]) s.add_runtime_dependency(%q<actionmailer>, [">= 0.6.1"]) else s.add_dependency(%q<rake>, [">= 0.4.15"]) s.add_dependency(%q<activerecord>, [">= 1.6.0"]) s.add_dependency(%q<actionpack>, [">= 1.4.0"]) s.add_dependency(%q<actionmailer>, [">= 0.6.1"]) end else s.add_dependency(%q<rake>, [">= 0.4.15"]) s.add_dependency(%q<activerecord>, [">= 1.6.0"]) s.add_dependency(%q<actionpack>, [">= 1.4.0"]) s.add_dependency(%q<actionmailer>, [">= 0.6.1"]) end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/lib/mocha/instance_method.rb
<gh_stars>1-10 require 'mocha/class_method' module Mocha class InstanceMethod < ClassMethod def hide_original_method super if singleton_method?(method) end def restore_original_method super if singleton_method?(hidden_method) end def method_exists?(method) return true if stubbee.public_methods(false).include?(method) return true if stubbee.protected_methods(false).include?(method) return true if stubbee.private_methods(false).include?(method) return false end def singleton_method?(method) __metaclass__ = stubbee.__metaclass__ return true if __metaclass__.public_instance_methods(false).include?(method) return true if __metaclass__.protected_instance_methods(false).include?(method) return true if __metaclass__.private_instance_methods(false).include?(method) return false end end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/acceptance/exception_rescue_test.rb
<reponame>beno/devise_sociable<gh_stars>1-10 require File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha' class ExceptionRescueTest < Test::Unit::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_unexpected_invocation_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') begin mock.some_method rescue => e flunk "should not rescue #{e.class}" end end assert_failed(test_result) assert_equal "unexpected invocation: #<Mock:mock>.some_method()", test_result.failure_message_lines[0] end def test_invocation_never_expected_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') mock.expects(:some_method).never begin mock.some_method rescue => e flunk "should not rescue #{e.class}" end end assert_failed(test_result) assert_equal "unexpected invocation: #<Mock:mock>.some_method()", test_result.failure_message_lines[0] end def test_unsatisfied_expectation_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') mock.expects(:some_method) end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #<Mock:mock>.some_method(any_parameters)" ], test_result.failure_message_lines end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/obsolete.rb
<filename>vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/obsolete.rb # # obsolete.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # module TMail # mail.rb 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 # facade.rb 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 # address.rb 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 # mbox.rb 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 # utils.rb 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
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/only_integer_matcher_spec.rb
require 'spec_helper' describe Shoulda::Matchers::ActiveModel::OnlyIntegerMatcher do context "given an attribute that only allows integer values" do before do define_model :example, :attr => :string do validates_numericality_of :attr, { :only_integer => true } end @model = Example.new end it "matches" do matcher = new_matcher(:attr) matcher.matches?(@model).should be_true end it "allows integer types" do matcher = new_matcher(:attr) matcher.allowed_types.should == "integer" end it "returns itself when given a message" do matcher = new_matcher(:attr) matcher.with_message("some message").should == matcher end end context "given an attribute that only allows integer values with a custom validation message" do before do define_model :example, :attr => :string do validates_numericality_of :attr, { :only_integer => true, :message => 'custom' } end @model = Example.new end it "should only allow integer values for that attribute with that message" do matcher = new_matcher(:attr) matcher.with_message(/custom/) matcher.matches?(@model).should be_true end it "should not allow integer values for that attribute with another message" do matcher = new_matcher(:attr) matcher.with_message(/wrong/) matcher.matches?(@model).should be_false end end context "given an attribute that allows values other than integers" do before do @model = define_model(:example, :attr => :string).new end it "does not match" do matcher = new_matcher(:attr) matcher.matches?(@model).should be_false end it "should fail with the ActiveRecord :not_an_integer message" do matcher = new_matcher(:attr) matcher.matches?(@model) matcher.failure_message.should include 'Expected errors to include "must be an integer"' end end def new_matcher(attribute) matcher = Shoulda::Matchers::ActiveModel::OnlyIntegerMatcher.new(attribute) end end
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/allow_mass_assignment_of_matcher_spec.rb
<filename>vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/active_model/allow_mass_assignment_of_matcher_spec.rb<gh_stars>1-10 require 'spec_helper' describe Shoulda::Matchers::ActiveModel::AllowMassAssignmentOfMatcher do describe "#description" do context 'without a role' do it 'includes the attribute name' do matcher = Shoulda::Matchers::ActiveModel::AllowMassAssignmentOfMatcher.new(:attr) matcher.description.should eq("allow mass assignment of attr") end end if active_model_3_1? context 'with a role' do it 'includes the attribute name and the role' do matcher = Shoulda::Matchers::ActiveModel::AllowMassAssignmentOfMatcher.new(:attr).as(:admin) matcher.description.should eq("allow mass assignment of attr as admin") end end end end context "an attribute that is blacklisted from mass-assignment" do let(:model) do define_model(:example, :attr => :string) do attr_protected :attr end.new end it "should reject being mass-assignable" do model.should_not allow_mass_assignment_of(:attr) end end context "an attribute that is not whitelisted for mass-assignment" do let(:model) do define_model(:example, :attr => :string, :other => :string) do attr_accessible :other end.new end it "should reject being mass-assignable" do model.should_not allow_mass_assignment_of(:attr) end end context "an attribute that is whitelisted for mass-assignment" do let(:model) do define_model(:example, :attr => :string) do attr_accessible :attr end.new end it "should accept being mass-assignable" do model.should allow_mass_assignment_of(:attr) end end context "an attribute not included in the mass-assignment blacklist" do let(:model) do define_model(:example, :attr => :string, :other => :string) do attr_protected :other end.new end it "should accept being mass-assignable" do model.should allow_mass_assignment_of(:attr) end end unless active_model_3_2? context "an attribute on a class with no protected attributes" do let(:model) { define_model(:example, :attr => :string).new } it "should accept being mass-assignable" do model.should allow_mass_assignment_of(:attr) end it "should assign a negative failure message" do matcher = allow_mass_assignment_of(:attr) matcher.matches?(model).should == true matcher.negative_failure_message.should_not be_nil end end end context "an attribute on a class with all protected attributes" do let(:model) do define_model(:example, :attr => :string) do attr_accessible end.new end it "should reject being mass-assignable" do model.should_not allow_mass_assignment_of(:attr) end end if active_model_3_1? context "an attribute included in the mass-assignment whitelist for admin role only" do let(:model) do define_model(:example, :attr => :string) do attr_accessible :attr, :as => :admin end.new end it "should reject being mass-assignable" do model.should_not allow_mass_assignment_of(:attr) end it "should accept being mass-assignable for admin" do model.should allow_mass_assignment_of(:attr).as(:admin) end end end end
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/lib/bourne/api.rb
<filename>vendor/bundle/gems/bourne-1.1.2/lib/bourne/api.rb<gh_stars>1-10 require 'mocha/api' require 'bourne/mockery' module Mocha # :nodoc: module API # Asserts that the given mock received the given method. # # Examples: # # assert_received(mock, :to_s) # assert_received(Radio, :new) {|expect| expect.with(1041) } # assert_received(radio, :volume) {|expect| expect.with(11).twice } def assert_received(mock, expected_method_name) matcher = have_received(expected_method_name) yield(matcher) if block_given? assert matcher.matches?(mock), matcher.failure_message end class InvalidHaveReceived < StandardError end class HaveReceived #:nodoc: def initialize(expected_method_name) @expected_method_name = expected_method_name @expectations = [] end def method_missing(method, *args, &block) @expectations << [method, args, block] self end def matches?(mock) if mock.respond_to?(:mocha) @mock = mock.mocha else @mock = mock end @expectation = Expectation.new(@mock, @expected_method_name) @expectations.each do |method, args, block| @expectation.send(method, *args, &block) end @expectation.invocation_count = invocation_count @expectation.verified? end def does_not_match?(mock) raise InvalidHaveReceived.new("should_not have_received(:#{@expected_method_name}) is invalid, please use" + " should have_received(:#{@expected_method_name}).never") end def failure_message message = "" if matching_stubs.empty? message << "unstubbed, " end message << @expectation.mocha_inspect end private def invocation_count matching_invocations.size end def matching_invocations invocations.select do |invocation| @expectation.match?(invocation.method_name, *invocation.arguments) end end def invocations Mockery.instance.invocations.select do |invocation| invocation.mock.equal?(@mock) end end def matching_stubs Mockery.instance.stubba.stubba_methods.select do |method| matching_stub?(method) end end def matching_stub?(method) method.mock.equal?(@mock) && method.method == @expected_method_name end end # :call-seq: # should have_received(method).with(arguments).times(times) # # Ensures that the given mock received the given method. # # Examples: # # mock.should have_received(:to_s) # Radio.should have_received(:new).with(1041) # radio.should have_received(:volume).with(11).twice def have_received(expected_method_name) HaveReceived.new(expected_method_name) end end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/generators/controller/controller_generator.rb
require 'rails_generator' class ControllerGenerator < Rails::Generator::Base attr_reader :actions def generate @actions = args # Controller class, functional test, and helper class. template "controller.rb", "app/controllers/#{file_name}_controller.rb" template "functional_test.rb", "test/functional/#{file_name}_controller_test.rb" template "helper.rb", "app/helpers/#{file_name}_helper.rb" # Create the views directory even if there are no actions. FileUtils.mkdir_p "app/views/#{file_name}" # Create a view for each action. actions.each do |action| template "view.rhtml", "app/views/#{file_name}/#{action}.rhtml", binding end end def full_class_name class_name + "Controller" end end
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/lib/bourne.rb
require 'mocha' require 'bourne/api'
beno/devise_sociable
devise_sociable.gemspec
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "devise_sociable" s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["beno"] s.date = "2013-02-02" s.description = "Track the last request and logout. Provides user.active? and User.actives methods" s.email = "<EMAIL>" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".bundle/config", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "devise_sociable.gemspec", "lib/devise_sociable.rb", "lib/devise_sociable/hooks/sociable.rb", "lib/devise_sociable/model.rb", "lib/devise_sociable/rails.rb", "lib/devise_sociable/version.rb", "lib/generators/devise_sociable/devise_sociable_generator.rb", "lib/generators/devise_sociable/templates/migration.rb", "test/support/helpers.rb", "test/test_devise_sociable_cache.rb", "test/test_devise_sociable_cookie.rb", "test/test_devise_sociable_server.rb", "test/test_helper.rb" ] s.homepage = "http://github.com/beno/devise_sociable" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Keep track of who is currently online." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, ["~> 4.0.2"]) # s.add_runtime_dependency(%q<warden>, ["~> 1.2.1"]) s.add_runtime_dependency(%q<devise>, ["~> 3.2.2"]) s.add_development_dependency(%q<sqlite3>, [">= 0"]) s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_runtime_dependency(%q<warden>, [">= 0"]) s.add_runtime_dependency(%q<devise>, [">= 0"]) s.add_runtime_dependency(%q<rails>, [">= 3.0.4"]) else s.add_dependency(%q<rails>, ["~> 3.2.8"]) s.add_dependency(%q<warden>, ["~> 1.2.1"]) s.add_dependency(%q<devise>, ["~> 2.2.2"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<warden>, [">= 0"]) s.add_dependency(%q<devise>, [">= 0"]) s.add_dependency(%q<rails>, [">= 3.0.4"]) end else s.add_dependency(%q<rails>, ["~> 3.2.8"]) s.add_dependency(%q<warden>, ["~> 1.2.1"]) s.add_dependency(%q<devise>, ["~> 2.2.2"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<warden>, [">= 0"]) s.add_dependency(%q<devise>, [">= 0"]) s.add_dependency(%q<rails>, [">= 3.0.4"]) end end
beno/devise_sociable
vendor/bundle/specifications/git-1.2.5.gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "git" s.version = "1.2.5" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = "2009-10-17" s.email = "<EMAIL>" s.extra_rdoc_files = ["README"] s.files = ["README"] s.homepage = "http://github.com/schacon/ruby-git" s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.requirements = ["git 1.6.0.0, or greater"] s.rubyforge_project = "git" s.rubygems_version = "1.8.23" s.summary = "Ruby/Git is a Ruby library that can be used to create, read and manipulate Git repositories by wrapping system calls to the git binary" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/lib/mocha/version.rb
<gh_stars>1-10 module Mocha VERSION = "0.10.5" end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/generators/controller/templates/functional_test.rb
<filename>vendor/bundle/gems/rails-0.9.5/generators/controller/templates/functional_test.rb require File.dirname(__FILE__) + '/../test_helper' require '<%= file_name %>_controller' # Re-raise errors caught by the controller. class <%= full_class_name %>; def rescue_action(e) raise e end; end class <%= full_class_name %>Test < Test::Unit::TestCase def setup @controller = <%= full_class_name %>.new @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new end # Replace this with your real tests. def test_truth assert true end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/scanner_r.rb
# # scanner_r.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # require 'tmail/config' module TMail class Scanner_R Version = '0.10.7' 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[$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
beno/devise_sociable
vendor/bundle/specifications/bourne-1.1.2.gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "bourne" s.version = "1.1.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = "2012-03-23" s.description = "Extends mocha to allow detailed tracking and querying of\n stub and mock invocations. Allows test spies using the have_received rspec\n matcher and assert_received for Test::Unit. Extracted from the\n jferris-mocha fork." s.email = "<EMAIL>" s.homepage = "http://github.com/thoughtbot/bourne" s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Adds test spies to mocha." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<mocha>, ["= 0.10.5"]) s.add_development_dependency(%q<rake>, [">= 0"]) else s.add_dependency(%q<mocha>, ["= 0.10.5"]) s.add_dependency(%q<rake>, [">= 0"]) end else s.add_dependency(%q<mocha>, ["= 0.10.5"]) s.add_dependency(%q<rake>, [">= 0"]) end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/install.rb
require 'rbconfig' require 'find' require 'ftools' include Config # this was adapted from rdoc's install.rb by ways 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 makedirs = %w{ action_mailer/vendor action_mailer/vendor/text action_mailer/vendor/tmail } makedirs.each {|f| File::makedirs(File.join($sitedir, *f.split(/\//)))} # deprecated files that should be removed # deprecated = %w{ } # files to install in library path files = %w- action_mailer.rb action_mailer/base.rb action_mailer/mail_helper.rb action_mailer/vendor/text/format.rb action_mailer/vendor/tmail.rb action_mailer/vendor/tmail/address.rb action_mailer/vendor/tmail/base64.rb action_mailer/vendor/tmail/config.rb action_mailer/vendor/tmail/encode.rb action_mailer/vendor/tmail/facade.rb action_mailer/vendor/tmail/header.rb action_mailer/vendor/tmail/info.rb action_mailer/vendor/tmail/loader.rb action_mailer/vendor/tmail/mail.rb action_mailer/vendor/tmail/mailbox.rb action_mailer/vendor/tmail/mbox.rb action_mailer/vendor/tmail/net.rb action_mailer/vendor/tmail/obsolete.rb action_mailer/vendor/tmail/parser.rb action_mailer/vendor/tmail/port.rb action_mailer/vendor/tmail/scanner.rb action_mailer/vendor/tmail/scanner_r.rb action_mailer/vendor/tmail/stringio.rb action_mailer/vendor/tmail/tmail.rb action_mailer/vendor/tmail/utils.rb - # the acual gruntwork Dir.chdir("lib") # File::safe_unlink *deprecated.collect{|f| File.join($sitedir, f.split(/\//))} files.each {|f| File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true) }
beno/devise_sociable
vendor/bundle/gems/bourne-1.1.2/test/unit/assert_received_test.rb
<filename>vendor/bundle/gems/bourne-1.1.2/test/unit/assert_received_test.rb require File.join(File.dirname(__FILE__), "..", "test_helper") require 'test_runner' require 'bourne/api' require 'bourne/mockery' require 'mocha/object' class AssertReceivedTest < Test::Unit::TestCase include Mocha include TestRunner include Mocha::API def teardown Mockery.reset_instance end class FakeMock def initialize(name) @name = name end def inspect @name end def mocha self end end def test_passes_if_invocation_exists method = :a_method mock = FakeMock.new('a mock') Mockery.instance.invocation(mock, method, []) assert_passes do assert_received(mock, method) end end def test_fails_if_invocation_doesnt_exist method = :a_method mock = FakeMock.new('a mock') assert_fails do assert_received(mock, method) end end def test_fails_if_invocation_exists_with_different_arguments method = :a_method mock = FakeMock.new('a mock') Mockery.instance.invocation(mock, method, [2, 1]) assert_fails do assert_received(mock, method) {|expect| expect.with(1, 2) } end end def test_passes_if_invocation_exists_with_wildcard_arguments method = :a_method mock = FakeMock.new('a mock') Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_received(mock, method) {|expect| expect.with(is_a(String)) } end end def test_passes_if_invocation_exists_with_exact_arguments method = :a_method mock = FakeMock.new('a mock') Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_received(mock, method) {|expect| expect.with('hello') } end end def test_fails_if_invocation_exists_only_on_other_mock method = :a_method mock = FakeMock.new('a mock') other = 'another mock' Mockery.instance.invocation(other, method, ['hello']) assert_fails do assert_received(mock, method) end end def test_passes_if_invocation_exists_for_impersonating_mock method = :a_method object = Object.new mock = FakeMock.new('a mock') class << object attr_accessor :mocha end object.mocha = mock Mockery.instance.invocation(mock, method, ['hello']) assert_passes do assert_received(object, method) {|expect| expect.with('hello') } end end def test_passes_if_invocation_count_correct method = :a_method mock = FakeMock.new('a mock') 2.times { Mockery.instance.invocation(mock, method, []) } assert_passes do assert_received(mock, method) {|expect| expect.twice } end end def test_fails_if_invocation_count_too_low method = :a_method mock = FakeMock.new('a mock') Mockery.instance.invocation(mock, method, []) assert_fails do assert_received(mock, method) {|expect| expect.twice } end end def test_fails_if_invocation_count_too_high method = :a_method mock = FakeMock.new('a mock') 2.times { Mockery.instance.invocation(mock, method, []) } assert_fails do assert_received(mock, method) {|expect| expect.once } end end def assert_passes(&block) assert ! fails?(&block) end def assert_fails(&block) assert fails?(&block) end def fails? begin yield false rescue FailedAssertion true end end end
beno/devise_sociable
vendor/bundle/gems/warden-1.0.6/lib/warden/version.rb
<gh_stars>1-10 # encoding: utf-8 module Warden VERSION = "1.0.6".freeze end
beno/devise_sociable
vendor/bundle/gems/rack-1.4.4/lib/rack/file.rb
<filename>vendor/bundle/gems/rack-1.4.4/lib/rack/file.rb require 'time' require 'rack/utils' require 'rack/mime' module Rack # Rack::File serves files below the +root+ directory given, according to the # path info of the Rack request. # e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file # as http://localhost:9292/passwd # # Handlers can detect if bodies are a Rack::File, and use mechanisms # like sendfile on the +path+. class File SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact) ALLOWED_VERBS = %w[GET HEAD] attr_accessor :root attr_accessor :path attr_accessor :cache_control alias :to_path :path def initialize(root, headers={}) @root = root # Allow a cache_control string for backwards compatibility if headers.instance_of? String warn \ "Rack::File headers parameter replaces cache_control after Rack 1.5." @headers = { 'Cache-Control' => headers } else @headers = headers end end def call(env) dup._call(env) end F = ::File def _call(env) unless ALLOWED_VERBS.include? env["REQUEST_METHOD"] return fail(405, "Method Not Allowed") end @path_info = Utils.unescape(env["PATH_INFO"]) parts = @path_info.split SEPS parts.inject(0) do |depth, part| case part when '', '.' depth when '..' return fail(404, "Not Found") if depth - 1 < 0 depth - 1 else depth + 1 end end @path = F.join(@root, *parts) available = begin F.file?(@path) && F.readable?(@path) rescue SystemCallError false end if available serving(env) else fail(404, "File not found: #{@path_info}") end end def serving(env) last_modified = F.mtime(@path).httpdate return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified response = [ 200, { "Last-Modified" => last_modified, "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain') }, env["REQUEST_METHOD"] == "HEAD" ? [] : self ] # Set custom headers @headers.each { |field, content| response[1][field] = content } if @headers # NOTE: # We check via File::size? whether this file provides size info # via stat (e.g. /proc files often don't), otherwise we have to # figure it out by reading the whole file into memory. size = F.size?(@path) || Utils.bytesize(F.read(@path)) ranges = Rack::Utils.byte_ranges(env, size) if ranges.nil? || ranges.length > 1 # No ranges, or multiple ranges (which we don't support): # TODO: Support multiple byte-ranges response[0] = 200 @range = 0..size-1 elsif ranges.empty? # Unsatisfiable. Return error, and file size: response = fail(416, "Byte range unsatisfiable") response[1]["Content-Range"] = "bytes */#{size}" return response else # Partial content: @range = ranges[0] response[0] = 206 response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}" size = @range.end - @range.begin + 1 end response[1]["Content-Length"] = size.to_s response end def each F.open(@path, "rb") do |file| file.seek(@range.begin) remaining_len = @range.end-@range.begin+1 while remaining_len > 0 part = file.read([8192, remaining_len].min) break unless part remaining_len -= part.length yield part end end end private def fail(status, body) body += "\n" [ status, { "Content-Type" => "text/plain", "Content-Length" => body.size.to_s, "X-Cascade" => "pass" }, [body] ] end end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/unit/thrower_test.rb
<filename>vendor/bundle/gems/mocha-0.10.5/test/unit/thrower_test.rb require File.expand_path('../../test_helper', __FILE__) require 'mocha/thrower' class ThrowerTest < Test::Unit::TestCase include Mocha def test_should_throw_tag thrower = Thrower.new(:tag) assert_throws(:tag) { thrower.evaluate } end def test_should_throw_tag_with_return_value thrower = Thrower.new(:tag, 'return-value') return_value = catch(:tag) { thrower.evaluate } assert_equal 'return-value', return_value end end
beno/devise_sociable
vendor/bundle/gems/rails-0.9.5/helpers/application.rb
<reponame>beno/devise_sociable # The filters added to this controller will be run for all controllers in the application. # Likewise will all the methods added be available for all controllers. class ApplicationController < ActionController::Base end
beno/devise_sociable
vendor/bundle/gems/warden-1.0.6/lib/warden/manager.rb
# encoding: utf-8 require 'warden/hooks' require 'warden/config' module Warden # The middleware for Rack Authentication # The middlware requires that there is a session upstream # The middleware injects an authentication object into # the rack environment hash class Manager extend Warden::Hooks attr_accessor :config # Initialize the middleware. If a block is given, a Warden::Config is yielded so you can properly # configure the Warden::Manager. # :api: public def initialize(app, options={}) default_strategies = options.delete(:default_strategies) @app, @config = app, Warden::Config.new(options) @config.default_strategies *default_strategies if default_strategies yield @config if block_given? self end # Invoke the application guarding for throw :warden. # If this is downstream from another warden instance, don't do anything. # :api: private def call(env) # :nodoc: return @app.call(env) if env['warden'] && env['warden'].manager != self env['warden'] = Proxy.new(env, self) result = catch(:warden) do @app.call(env) end result ||= {} case result when Array if result.first == 401 && intercept_401?(env) process_unauthenticated(env) else result end when Hash process_unauthenticated(env, result) end end # :api: private def _run_callbacks(*args) #:nodoc: self.class._run_callbacks(*args) end class << self # Prepares the user to serialize into the session. # Any object that can be serialized into the session in some way can be used as a "user" object # Generally however complex object should not be stored in the session. # If possible store only a "key" of the user object that will allow you to reconstitute it. # # Example: # Warden::Manager.serialize_into_session{ |user| user.id } # # :api: public def serialize_into_session(&block) Warden::SessionSerializer.send :define_method, :serialize, &block end # Reconstitues the user from the session. # Use the results of user_session_key to reconstitue the user from the session on requests after the initial login # # Example: # Warden::Manager.serialize_from_session{ |id| User.get(id) } # # :api: public def serialize_from_session(&block) Warden::SessionSerializer.send :define_method, :deserialize, &block end end private def intercept_401?(env) config[:intercept_401] && !env['warden'].custom_failure? end # When a request is unauthentiated, here's where the processing occurs. # It looks at the result of the proxy to see if it's been executed and what action to take. # :api: private def process_unauthenticated(env, options={}) options[:action] ||= "unauthenticated" proxy = env['warden'] result = options[:result] || proxy.result case result when :redirect body = proxy.message || "You are being redirected to #{proxy.headers['Location']}" [proxy.status, proxy.headers, [body]] when :custom proxy.custom_response else call_failure_app(env, options) end end # Calls the failure app. # The before_failure hooks are run on each failure # :api: private def call_failure_app(env, options = {}) if config.failure_app options.merge!(:attempted_path => ::Rack::Request.new(env).fullpath) env["PATH_INFO"] = "/#{options[:action]}" env["warden.options"] = options _run_callbacks(:before_failure, env, options) config.failure_app.call(env).to_a else raise "No Failure App provided" end end # call_failure_app end end # Warden
beno/devise_sociable
test/test_devise_sociable_server.rb
<gh_stars>1-10 require 'test_helper' class TestDeviseSociableServer < ActiveSupport::TestCase setup do setup_rails(ActiveRecord::SessionStore) @user1 = create_user @user2 = create_user create_session(@user1, 12.minutes.ago) create_session(@user2, 8.minutes.ago) create_anonymous_session end teardown do ActiveRecord::SessionStore::Session.delete_all User.delete_all end test "server: should have active users" do assert User.actives(10.minutes.ago) == [@user2] end test "server: user can be (in)active" do assert @user1.active?(10.minutes.ago) == false assert @user2.active?(10.minutes.ago) == true end end
beno/devise_sociable
vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/independent/delegate_matcher_spec.rb
<filename>vendor/bundle/gems/shoulda-matchers-1.4.2/spec/shoulda/independent/delegate_matcher_spec.rb require 'spec_helper' describe Shoulda::Matchers::Independent::DelegateMatcher do it 'supports chaining on #to' do matcher = delegate_method(:method) matcher.to(:another_method).should == matcher end it 'supports chaining on #with_arguments' do matcher = delegate_method(:method) matcher.with_arguments(1, 2, 3).should == matcher end it 'supports chaining on #as' do matcher = delegate_method(:method) matcher.as(:some_other_method).should == matcher end it 'should raise an error if no delegation target is defined' do object = Object.new expect { object.should delegate_method(:name) }.to raise_exception Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError end it 'should raise an error if called with #should_not' do object = Object.new expect { object.should_not delegate_method(:name).to(:anyone) }.to raise_exception Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher end context 'given a method that does not delegate' do before do define_class(:post_office) do def deliver_mail :delivered end end end it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which method should have been delegated' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman' matcher.failure_message.should == message end it 'uses the proper syntax for class methods in errors' do matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(PostOffice) message = 'Expected PostOffice.deliver_mail to delegate to PostOffice.mailman' matcher.failure_message.should == message end end context 'given a method that delegates properly' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail end def mailman Mailman.new end end end it 'matches' do post_office = PostOffice.new post_office.should delegate_method(:deliver_mail).to(:mailman) end end context 'given a method that delegates properly with certain arguments' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail('221B Baker St.', :hastily => true) end def mailman Mailman.new end end end context 'when given the correct arguments' do it 'matches' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('221B Baker St.', :hastily => true) post_office.should matcher end end context 'when not given the correct arguments' do it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('123 Nowhere Ln.') matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which arguments were expected' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('123 Nowhere Ln.') matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman with arguments: ["123 Nowhere Ln."]' matcher.failure_message.should == message end end end context 'given a method that delegates properly to a method of a different name' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail_and_avoid_dogs end def mailman Mailman.new end end end context 'when given the correct method name' do it 'matches' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:deliver_mail_and_avoid_dogs) post_office.should matcher end end context 'when given an incorrect method name' do it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:watch_tv) matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which method was expected' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:watch_tv) matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman as :watch_tv' matcher.failure_message.should == message end end end end describe Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError do it 'has a useful message' do error = Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError.new error.message.should include 'Delegation needs a target' end end describe Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher do it 'has a useful message' do error = Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher.new error.message.should include 'does not support #should_not' end end
beno/devise_sociable
test/test_devise_sociable_cache.rb
require 'test_helper' class TestDeviseSociableCache < ActiveSupport::TestCase setup do setup_rails(ActionDispatch::Session::CookieStore) @user1 = create_user(last_request_at:8.minutes.ago) @user2 = create_user(last_request_at:12.minutes.ago) @user3 = create_user(last_request_at:8.minutes.ago, last_sign_out_at:5.minutes.ago) end teardown do User.delete_all end test "should cache active users" do User.cache_actives(10.minutes.ago) assert User.actives_cache == { @user1.id => @user1 }, 'actives cache' end test "should cache more active users" do @user3.update_attribute(:last_request_at, 1.minute.ago) User.cache_actives(15.minutes.ago) assert User.actives_cache == { @user1.id => @user1, @user2.id => @user2, @user3.id => @user3 }, 'actives cache more' end test "should return cached value if cached" do User.cache_actives(10.minutes.ago) @user1.update_attribute(:last_sign_out_at, 1.minute.ago) assert User.cached?(@user1) == true, 'cached value' assert @user1.active?(10.minutes.ago) == true, 'cached value' end test "should return new value if cache updated" do @user1.update_attribute(:last_sign_out_at, 1.minute.ago) User.cache_actives(10.minutes) assert User.cached?(@user1) == false, 'cached value updated' assert @user1.active?(10.minutes) == false, 'cached value updated' end test "should be removed from cache" do User.cache_actives(10.minutes) @user1.update_attribute(:last_sign_out_at, 1.minute.ago) @user1.deactivate! assert User.cached?(@user1) == false, 'cached value removed' end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/port.rb
# # port.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # 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.id.hash end def inspect "#<#{self.class}:id=#{sprintf '0x%x', @buffer.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
beno/devise_sociable
vendor/bundle/gems/shoulda-context-1.0.2/lib/shoulda/context.rb
<reponame>beno/devise_sociable<gh_stars>1-10 if !defined?(Test::Unit::TestCase) require 'test/unit/testcase' end require 'shoulda/context/version' require 'shoulda/context/proc_extensions' require 'shoulda/context/assertions' require 'shoulda/context/context' require 'shoulda/context/autoload_macros' class Test::Unit::TestCase include Shoulda::Context::Assertions include Shoulda::Context::InstanceMethods extend Shoulda::Context::ClassMethods end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/info.rb
<reponame>beno/devise_sociable # # info.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # module TMail Version = '0.10.7' Copyright = 'Copyright (c) 1998-2002 Minero Aoki' end
beno/devise_sociable
lib/devise_sociable/hooks/sociable.rb
<reponame>beno/devise_sociable<filename>lib/devise_sociable/hooks/sociable.rb Warden::Manager.after_set_user do |record, warden, opts| if record.class.uses_cookies? record.update_attribute('last_request_at', Time.zone.now) else scope = opts[:scope] warden.session(scope)['last_request_at'] = Time.zone.now end end Warden::Manager.before_logout do |record, warden, opts| begin record.deactivate! if record.class.uses_cookies? record.update_attribute('last_sign_out_at', Time.zone.now) end rescue NoMethodError #catch logout calls with no active user end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/test_runner.rb
<gh_stars>1-10 require 'test/unit/testcase' if defined?(MiniTest) require 'mocha/integration/mini_test' require File.expand_path('../mini_test_result', __FILE__) else require 'test/unit/testresult' end module TestRunner def run_as_test(test_result = nil, &block) test_class = Class.new(Test::Unit::TestCase) do define_method(:test_me, &block) end test = test_class.new(:test_me) if defined?(Test::Unit::TestResult) test_result ||= Test::Unit::TestResult.new test.run(test_result) {} class << test_result attr_reader :failures, :errors def failure_messages failures.map { |failure| failure.message } end def failure_message_lines failure_messages.map { |message| message.split("\n") }.flatten end def error_messages errors.map { |error| error.message } end end else runner = MiniTest::Unit.new test.run(runner) test_result = MiniTestResult.new(runner, test) end test_result end def assert_passed(test_result) flunk "Test failed unexpectedly with message: #{test_result.failures}" if test_result.failure_count > 0 flunk "Test failed unexpectedly with message: #{test_result.errors}" if test_result.error_count > 0 end def assert_failed(test_result) flunk "Test passed unexpectedly" if test_result.passed? end end
beno/devise_sociable
vendor/bundle/gems/mocha-0.10.5/test/acceptance/acceptance_test_helper.rb
require File.expand_path('../../test_helper', __FILE__) require 'test_runner' require 'mocha/configuration' require 'introspection' module AcceptanceTest class FakeLogger attr_reader :warnings def initialize @warnings = [] end def warn(message) @warnings << message end end attr_reader :logger include TestRunner def setup_acceptance_test Mocha::Configuration.reset_configuration @logger = FakeLogger.new mockery = Mocha::Mockery.instance @original_logger = mockery.logger mockery.logger = @logger end def teardown_acceptance_test Mocha::Configuration.reset_configuration Mocha::Mockery.instance.logger = @original_logger end include Introspection::Assertions end
beno/devise_sociable
vendor/bundle/gems/devise-1.5.4/lib/devise/path_checker.rb
<reponame>beno/devise_sociable module Devise class PathChecker include Rails.application.routes.url_helpers def self.default_url_options(*args) ApplicationController.default_url_options(*args) end def initialize(env, scope) @current_path = "/#{env["SCRIPT_NAME"]}/#{env["PATH_INFO"]}".squeeze("/") @scope = scope end def signing_out? route = "destroy_#{@scope}_session_path" respond_to?(route) && @current_path == send(route) end end end
beno/devise_sociable
vendor/bundle/gems/devise-1.5.4/lib/devise/rails.rb
require 'devise/rails/routes' require 'devise/rails/warden_compat' module Devise class Engine < ::Rails::Engine config.devise = Devise # Initialize Warden and copy its configurations. config.app_middleware.use Warden::Manager do |config| Devise.warden_config = config end # Force routes to be loaded if we are doing any eager load. config.before_eager_load { |app| app.reload_routes! } initializer "devise.url_helpers" do Devise.include_helpers(Devise::Controllers) end initializer "devise.omniauth" do |app| Devise.omniauth_configs.each do |provider, config| app.middleware.use config.strategy_class, *config.args do |strategy| config.strategy = strategy end end if Devise.omniauth_configs.any? Devise.include_helpers(Devise::OmniAuth) end end initializer "devise.mongoid_version_warning" do if defined?(Mongoid) require 'mongoid/version' if Mongoid::VERSION.to_f < 2.1 puts "\n[DEVISE] Please note that Mongoid versions prior to 2.1 handle dirty model " \ "object attributes in such a way that the Devise `validatable` module will not apply " \ "its usual uniqueness and format validations for the email field. It is recommended " \ "that you upgrade to Mongoid 2.1+ for this and other fixes, but if for some reason you " \ "are unable to do so, you should add these validations manually.\n" end end end end end
beno/devise_sociable
test/test_devise_sociable_cookie.rb
require 'test_helper' class TestDeviseSociableCookies < ActiveSupport::TestCase setup do setup_rails(ActionDispatch::Session::CookieStore) @user1 = create_user(last_request_at:8.minutes.ago) @user2 = create_user(last_request_at:12.minutes.ago) @user3 = create_user(last_request_at:8.minutes.ago, last_sign_out_at:5.minutes.ago) end teardown do User.delete_all end test "should have active users" do assert User.actives(10.minutes.ago) == [@user1], 'actives' end test "user can be (in)active" do assert @user1.active?(10.minutes.ago) == true, 'user 1' assert @user2.active?(10.minutes) == false, 'user 2' assert @user3.active?(10.minutes.ago) == false, 'user 3' end end
beno/devise_sociable
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/utils.rb
# # utils.rb # # Copyright (c) 1998-2003 <NAME> <<EMAIL>> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # module TMail class SyntaxError < StandardError; end def TMail.new_boundary 'mimepart_' + random_tag end def TMail.new_message_id( fqdn = nil ) fqdn ||= ::Socket.gethostname "<#{random_tag()}@#{fqdn}.tmail>" end def TMail.random_tag @uniq += 1 t = Time.now sprintf('%x%x_%x%x%d%x', t.to_i, t.tv_usec, $$, Thread.current.id, @uniq, rand(255)) end private_class_method :random_tag @uniq = 0 module TextUtils aspecial = '()<>[]:;.@\\,"' tspecial = '()<>[];:@\\,"/?=' lwsp = " \t\r\n" control = '\x00-\x1f\x7f-\xff' ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{lwsp}]/n PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{lwsp}]/n CONTROL_CHAR = /[#{control}]/n def atom_safe?( str ) not ATOM_UNSAFE === str end def quote_atom( str ) (ATOM_UNSAFE === str) ? dquote(str) : str end def quote_phrase( str ) (PHRASE_UNSAFE === str) ? dquote(str) : str end def token_safe?( str ) not TOKEN_UNSAFE === str end def quote_token( str ) (TOKEN_UNSAFE === str) ? dquote(str) : str end def dquote( str ) '"' + str.gsub(/["\\]/n) {|s| '\\' + s } + '"' end private :dquote def join_domain( arr ) arr.map {|i| if /\A\[.*\]\z/ === i i else quote_atom(i) end }.join('.') end 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 } 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 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[$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 NKF.nkf(NKF_FLAGS[$KCODE], m.post_match.gsub(/%[\da-f]{2}/in) {|s| s[1,2].hex.chr }) end end end
beno/devise_sociable
vendor/bundle/specifications/jeweler-1.8.4.gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "jeweler" s.version = "1.8.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = "2012-06-22" s.description = "Simple and opinionated helper for creating Rubygem projects on GitHub" s.email = "<EMAIL>" s.executables = ["jeweler"] s.extra_rdoc_files = ["ChangeLog.markdown", "LICENSE.txt", "README.markdown"] s.files = ["bin/jeweler", "ChangeLog.markdown", "LICENSE.txt", "README.markdown"] s.homepage = "http://github.com/technicalpickles/jeweler" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Opinionated tool for creating and managing RubyGem projects" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rake>, [">= 0"]) s.add_runtime_dependency(%q<git>, [">= 1.2.5"]) s.add_runtime_dependency(%q<bundler>, ["~> 1.0"]) s.add_runtime_dependency(%q<rdoc>, [">= 0"]) s.add_development_dependency(%q<yard>, ["~> 0.7.4"]) s.add_development_dependency(%q<rdoc>, [">= 0"]) s.add_development_dependency(%q<bluecloth>, [">= 0"]) s.add_development_dependency(%q<cucumber>, ["~> 1.1.4"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<git>, [">= 1.2.5"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.7.4"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<bluecloth>, [">= 0"]) s.add_dependency(%q<cucumber>, ["~> 1.1.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<git>, [">= 1.2.5"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.7.4"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<bluecloth>, [">= 0"]) s.add_dependency(%q<cucumber>, ["~> 1.1.4"]) s.add_dependency(%q<rcov>, [">= 0"]) end end