repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/latlon.rb | lib/geocoder/results/latlon.rb | require 'geocoder/results/base'
module Geocoder::Result
class Latlon < Base
def city
address_components["city"]
end
def coordinates
[@data['lat'].to_f, @data['lon'].to_f]
end
def country
"United States" # LatLon.io only supports the US
end
def country_code
"US" # LatLon.io only supports the US
end
def formatted_address(format = :full)
address_components["address"]
end
alias_method :address, :formatted_address
def number
address_components["number"]
end
def prefix
address_components["prefix"]
end
def state
address_components["state"]
end
alias_method :state_code, :state
def street
[street_name, street_type].compact.join(' ')
end
def street_name
address_components["street_name"]
end
def street_type
address_components["street_type"]
end
def suffix
address_components["suffix"]
end
def unit
address_components["unit"]
end
def zip
address_components["zip"]
end
alias_method :postal_code, :zip
private
def address_components
@data["address"] || {}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/telize.rb | lib/geocoder/results/telize.rb | require 'geocoder/results/base'
module Geocoder::Result
class Telize < Base
def city
@data['city']
end
def state
@data['region']
end
def state_code
@data['region_code']
end
def country
@data['country']
end
def country_code
@data['country_code']
end
def postal_code
@data['postal_code']
end
def self.response_attributes
%w[timezone isp dma_code area_code ip asn continent_code country_code3]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/bing.rb | lib/geocoder/results/bing.rb | require 'geocoder/results/base'
module Geocoder::Result
class Bing < Base
def address(format = :full)
@data['address']['formattedAddress']
end
def city
@data['address']['locality']
end
def state_code
@data['address']['adminDistrict']
end
alias_method :state, :state_code
def country
@data['address']['countryRegion']
end
alias_method :country_code, :country
def postal_code
@data['address']['postalCode'].to_s
end
def coordinates
@data['point']['coordinates']
end
def address_data
@data['address']
end
def viewport
@data['bbox']
end
def self.response_attributes
%w[bbox name confidence entityType]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipstack.rb | lib/geocoder/results/ipstack.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ipstack < Base
def address(format = :full)
s = region_code.empty? ? "" : ", #{region_code}"
"#{city}#{s} #{zip}, #{country_name}".sub(/^[ ,]*/, "")
end
def state
@data['region_name']
end
def state_code
@data['region_code']
end
def country
@data['country_name']
end
def postal_code
@data['zip'] || @data['zipcode'] || @data['zip_code']
end
def self.response_attributes
[
['ip', ''],
['hostname', ''],
['continent_code', ''],
['continent_name', ''],
['country_code', ''],
['country_name', ''],
['region_code', ''],
['region_name', ''],
['city', ''],
['zip', ''],
['latitude', 0],
['longitude', 0],
['location', {}],
['time_zone', {}],
['currency', {}],
['connection', {}],
['security', {}],
]
end
response_attributes.each do |attr, default|
define_method attr do
@data[attr] || default
end
end
def metro_code
Geocoder.log(:warn, "Ipstack does not implement `metro_code` in api results. Please discontinue use.")
0 # no longer implemented by ipstack
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipregistry.rb | lib/geocoder/results/ipregistry.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ipregistry < Base
def initialize(data)
super
@data = flatten_hash(data)
end
def coordinates
[@data['location_latitude'], @data['location_longitude']]
end
def flatten_hash(hash)
hash.each_with_object({}) do |(k, v), h|
if v.is_a? Hash
flatten_hash(v).map do |h_k, h_v|
h["#{k}_#{h_k}".to_s] = h_v
end
else
h[k] = v
end
end
end
private :flatten_hash
def city
@data['location_city']
end
def country
@data['location_country_name']
end
def country_code
@data['location_country_code']
end
def postal_code
@data['location_postal']
end
def state
@data['location_region_name']
end
def state_code
@data['location_region_code']
end
# methods for fields specific to Ipregistry
def ip
@data["ip"]
end
def type
@data["type"]
end
def hostname
@data["hostname"]
end
def carrier_name
@data["carrier_name"]
end
def carrier_mcc
@data["carrier_mcc"]
end
def carrier_mnc
@data["carrier_mnc"]
end
def connection_asn
@data["connection_asn"]
end
def connection_domain
@data["connection_domain"]
end
def connection_organization
@data["connection_organization"]
end
def connection_type
@data["connection_type"]
end
def currency_code
@data["currency_code"]
end
def currency_name
@data["currency_name"]
end
def currency_plural
@data["currency_plural"]
end
def currency_symbol
@data["currency_symbol"]
end
def currency_symbol_native
@data["currency_symbol_native"]
end
def currency_format_negative_prefix
@data["currency_format_negative_prefix"]
end
def currency_format_negative_suffix
@data["currency_format_negative_suffix"]
end
def currency_format_positive_prefix
@data["currency_format_positive_prefix"]
end
def currency_format_positive_suffix
@data["currency_format_positive_suffix"]
end
def location_continent_code
@data["location_continent_code"]
end
def location_continent_name
@data["location_continent_name"]
end
def location_country_area
@data["location_country_area"]
end
def location_country_borders
@data["location_country_borders"]
end
def location_country_calling_code
@data["location_country_calling_code"]
end
def location_country_capital
@data["location_country_capital"]
end
def location_country_code
@data["location_country_code"]
end
def location_country_name
@data["location_country_name"]
end
def location_country_population
@data["location_country_population"]
end
def location_country_population_density
@data["location_country_population_density"]
end
def location_country_flag_emoji
@data["location_country_flag_emoji"]
end
def location_country_flag_emoji_unicode
@data["location_country_flag_emoji_unicode"]
end
def location_country_flag_emojitwo
@data["location_country_flag_emojitwo"]
end
def location_country_flag_noto
@data["location_country_flag_noto"]
end
def location_country_flag_twemoji
@data["location_country_flag_twemoji"]
end
def location_country_flag_wikimedia
@data["location_country_flag_wikimedia"]
end
def location_country_languages
@data["location_country_languages"]
end
def location_country_tld
@data["location_country_tld"]
end
def location_region_code
@data["location_region_code"]
end
def location_region_name
@data["location_region_name"]
end
def location_city
@data["location_city"]
end
def location_postal
@data["location_postal"]
end
def location_latitude
@data["location_latitude"]
end
def location_longitude
@data["location_longitude"]
end
def location_language_code
@data["location_language_code"]
end
def location_language_name
@data["location_language_name"]
end
def location_language_native
@data["location_language_native"]
end
def location_in_eu
@data["location_in_eu"]
end
def security_is_bogon
@data["security_is_bogon"]
end
def security_is_cloud_provider
@data["security_is_cloud_provider"]
end
def security_is_tor
@data["security_is_tor"]
end
def security_is_tor_exit
@data["security_is_tor_exit"]
end
def security_is_proxy
@data["security_is_proxy"]
end
def security_is_anonymous
@data["security_is_anonymous"]
end
def security_is_abuser
@data["security_is_abuser"]
end
def security_is_attacker
@data["security_is_attacker"]
end
def security_is_threat
@data["security_is_threat"]
end
def time_zone_id
@data["time_zone_id"]
end
def time_zone_abbreviation
@data["time_zone_abbreviation"]
end
def time_zone_current_time
@data["time_zone_current_time"]
end
def time_zone_name
@data["time_zone_name"]
end
def time_zone_offset
@data["time_zone_offset"]
end
def time_zone_in_daylight_saving
@data["time_zone_in_daylight_saving"]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ip2location_lite.rb | lib/geocoder/results/ip2location_lite.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ip2locationLite < Base
def coordinates
[@data[:latitude], @data[:longitude]]
end
def city
@data[:city]
end
def state
@data[:region]
end
def state_code
"" # Not available in Maxmind's database
end
def country
@data[:country_long]
end
def country_code
@data[:country_short]
end
def postal_code
@data[:zipcode]
end
def self.response_attributes
%w[country_short country_long region latitude longitude isp
domain netspeed areacode iddcode timezone zipcode weatherstationname
weatherstationcode mcc mnc mobilebrand elevation usagetype addresstype
category district asn as]
end
response_attributes.each do |a|
define_method a do
@data[a] || ""
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipdata_co.rb | lib/geocoder/results/ipdata_co.rb | require 'geocoder/results/base'
module Geocoder::Result
class IpdataCo < Base
def city
@data['city']
end
def state
@data['region']
end
def state_code
@data['region_code']
end
def country
@data['country_name']
end
def country_code
@data['country_code']
end
def postal_code
@data['postal']
end
def self.response_attributes
%w[ip asn organisation currency currency_symbol calling_code flag time_zone is_eu]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/mapquest.rb | lib/geocoder/results/mapquest.rb | require 'geocoder/results/base'
module Geocoder::Result
class Mapquest < Base
def coordinates
%w[lat lng].map{ |l| @data["latLng"][l] }
end
def city
@data['adminArea5']
end
def street
@data['street']
end
def state
@data['adminArea3']
end
def county
@data['adminArea4']
end
alias_method :state_code, :state
#FIXME: these might not be right, unclear with MQ documentation
alias_method :province, :state
alias_method :province_code, :state
def postal_code
@data['postalCode'].to_s
end
def country
@data['adminArea1']
end
def country_code
country
end
def address
[street, city, state, postal_code, country].reject{|s| s.length == 0 }.join(", ")
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ban_data_gouv_fr.rb | lib/geocoder/results/ban_data_gouv_fr.rb | # encoding: utf-8
require 'geocoder/results/base'
module Geocoder::Result
class BanDataGouvFr < Base
STATE_CODE_MAPPINGS = {
"Guadeloupe" => "01",
"Martinique" => "02",
"Guyane" => "03",
"La Réunion" => "04",
"Mayotte" => "06",
"Île-de-France" => "11",
"Centre-Val de Loire" => "24",
"Bourgogne-Franche-Comté" => "27",
"Normandie" => "28",
"Hauts-de-France" => "32",
"Grand Est" => "44",
"Pays de la Loire" => "52",
"Bretagne" => "53",
"Nouvelle-Aquitaine" => "75",
"Occitanie" => "76",
"Auvergne-Rhône-Alpes" => "84",
"Provence-Alpes-Côte d'Azur" => "93",
"Corse" => "94"
}.freeze
#### BASE METHODS ####
def self.response_attributes
%w[limit attribution version licence type features center]
end
response_attributes.each do |a|
unless method_defined?(a)
define_method a do
@data[a]
end
end
end
#### BEST RESULT ####
def result
features[0] if features.any?
end
#### GEOMETRY ####
def geometry
result['geometry'] if result
end
def precision
geometry['type'] if geometry
end
def coordinates
coords = geometry["coordinates"]
return [coords[1].to_f, coords[0].to_f]
end
#### PROPERTIES ####
# List of raw attrbutes returned by BAN data gouv fr API:
#
# :id => [string] UUID of the result, said to be not stable
# atm, based on IGN reference (Institut national de
# l'information géographique et forestière)
#
# :type => [string] result type (housenumber, street, city,
# town, village, locality)
#
# :score => [float] value between 0 and 1 giving result's
# relevancy
#
# :housenumber => [string] street number and extra information
# (bis, ter, A, B)
#
# :street => [string] street name
#
# :name => [string] housenumber and street name
#
# :postcode => [string] city post code (used for mails by La Poste,
# beware many cities got severeal postcodes)
#
# :citycode => [string] city code (INSEE reference,
# consider it as a french institutional UUID)
#
# :city => [string] city name
#
# :context => [string] department code, department name and
# region code
#
# :label => [string] full address without state, country name
# and country code
#
# CITIES ONLY PROPERTIES
#
# :adm_weight => [string] administrative weight (importance) of
# the city
#
# :population => [float] number of inhabitants with a 1000 factor
#
# For up to date doc (in french only) : https://adresse.data.gouv.fr/api/
#
def properties
result['properties'] if result
end
# List of usable Geocoder results' methods
#
# score => [float] result relevance 0 to 1
#
# location_id => [string] location's IGN UUID
#
# result_type => [string] housenumber / street / city
# / town / village / locality
#
# international_address => [string] full address with country code
#
# national_address => [string] full address with country code
#
# street_address => [string] housenumber + extra inf
# + street name
#
# street_number => [string] housenumber + extra inf
# (bis, ter, etc)
#
# street_name => [string] street's name
#
# city_name => [string] city's name
#
# city_code => [string] city's INSEE UUID
#
# postal_code => [string] city's postal code (used for mails)
#
# context => [string] city's department code, department
# name and region name
#
# demartment_name => [string] city's department name
#
# department_code => [string] city's department INSEE UUID
#
# region_name => [string] city's region name
#
# population => [string] city's inhabitants count
#
# administrative_weight => [integer] city's importance on a scale
# from 6 (capital city) to 1 (regular village)
#
def score
properties['score']
end
def location_id
properties['id']
end
# Types
#
# housenumber
# street
# city
# town
# village
# locality
#
def result_type
properties['type']
end
def international_address
"#{national_address}, #{country}"
end
def national_address
properties['label']
end
def street_address
properties['name']
end
def street_number
properties['housenumber']
end
def street_name
properties['street']
end
def city_name
properties['city']
end
def city_code
properties['citycode']
end
def postal_code
properties['postcode']
end
def context
properties['context'].split(/,/).map(&:strip)
end
def department_code
context[0] if context.length > 0
end
# Monkey logic to handle fact Paris is both a city and a department
# in Île-de-France region
def department_name
if context.length > 1
if context[1] == "Île-de-France"
"Paris"
else
context[1]
end
end
end
def region_name
if context.length == 2 && context[1] == "Île-de-France"
context[1]
elsif context.length > 2
context[2]
end
end
def region_code
STATE_CODE_MAPPINGS[region_name]
end
def country
"France"
end
# Country code types
# FR : France
# GF : Guyane Française
# RE : Réunion
# NC : Nouvelle-Calédonie
# GP : Guadeloupe
# MQ : Martinique
# MU : Maurice
# PF : Polynésie française
#
# Will need refacto to handle different country codes, but BAN API
# is currently mainly designed for geocode FR country code addresses
def country_code
"FR"
end
#### ALIAS METHODS ####
alias_method :address, :international_address
alias_method :street, :street_name
alias_method :city, :city_name
alias_method :state, :region_name
alias_method :state_code, :region_code
#### CITIES' METHODS ####
def population
(properties['population'].to_f * 1000).to_i if city?(result_type)
end
def administrative_weight
properties['adm_weight'].to_i if city?(result_type)
end
private
def city?(result_type)
result_type == 'municipality'
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/abstract_api.rb | lib/geocoder/results/abstract_api.rb | require 'geocoder/results/base'
module Geocoder
module Result
class AbstractApi < Base
##
# Geolocation
def state
@data['region']
end
def state_code
@data['region_iso_code']
end
def city
@data["city"]
end
def city_geoname_id
@data["city_geoname_id"]
end
def region_geoname_id
@data["region_geoname_id"]
end
def postal_code
@data["postal_code"]
end
def country
@data["country"]
end
def country_code
@data["country_code"]
end
def country_geoname_id
@data["country_geoname_id"]
end
def country_is_eu
@data["country_is_eu"]
end
def continent
@data["continent"]
end
def continent_code
@data["continent_code"]
end
def continent_geoname_id
@data["continent_geoname_id"]
end
##
# Security
def is_vpn?
@data.dig "security", "is_vpn"
end
##
# Timezone
def timezone_name
@data.dig "timezone", "name"
end
def timezone_abbreviation
@data.dig "timezone", "abbreviation"
end
def timezone_gmt_offset
@data.dig "timezone", "gmt_offset"
end
def timezone_current_time
@data.dig "timezone", "current_time"
end
def timezone_is_dst
@data.dig "timezone", "is_dst"
end
##
# Flag
def flag_emoji
@data.dig "flag", "emoji"
end
def flag_unicode
@data.dig "flag", "unicode"
end
def flag_png
@data.dig "flag", "png"
end
def flag_svg
@data.dig "flag", "svg"
end
##
# Currency
def currency_currency_name
@data.dig "currency", "currency_name"
end
def currency_currency_code
@data.dig "currency", "currency_code"
end
##
# Connection
def connection_autonomous_system_number
@data.dig "connection", "autonomous_system_number"
end
def connection_autonomous_system_organization
@data.dig "connection", "autonomous_system_organization"
end
def connection_connection_type
@data.dig "connection", "connection_type"
end
def connection_isp_name
@data.dig "connection", "isp_name"
end
def connection_organization_name
@data.dig "connection", "organization_name"
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/uk_ordnance_survey_names.rb | lib/geocoder/results/uk_ordnance_survey_names.rb | require 'geocoder/results/base'
require 'easting_northing'
module Geocoder::Result
class UkOrdnanceSurveyNames < Base
def coordinates
@coordinates ||= Geocoder::EastingNorthing.new(
easting: data['GEOMETRY_X'],
northing: data['GEOMETRY_Y'],
).lat_lng
end
def city
is_postcode? ? data['DISTRICT_BOROUGH'] : data['NAME1']
end
def county
data['COUNTY_UNITARY']
end
alias state county
def county_code
code_from_uri data['COUNTY_UNITARY_URI']
end
alias state_code county_code
def province
data['REGION']
end
def province_code
code_from_uri data['REGION_URI']
end
def postal_code
is_postcode? ? data['NAME1'] : ''
end
def country
'United Kingdom'
end
def country_code
'UK'
end
private
def is_postcode?
data['LOCAL_TYPE'] == 'Postcode'
end
def code_from_uri(uri)
return '' if uri.nil?
uri.split('/').last
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipqualityscore.rb | lib/geocoder/results/ipqualityscore.rb | require 'geocoder/results/base'
module Geocoder
module Result
class Ipqualityscore < Base
def self.key_method_mappings
{
'request_id' => :request_id,
'success' => :success?,
'message' => :message,
'city' => :city,
'region' => :state,
'country_code' => :country_code,
'mobile' => :mobile?,
'fraud_score' => :fraud_score,
'ISP' => :isp,
'ASN' => :asn,
'organization' => :organization,
'is_crawler' => :crawler?,
'host' => :host,
'proxy' => :proxy?,
'vpn' => :vpn?,
'tor' => :tor?,
'active_vpn' => :active_vpn?,
'active_tor' => :active_tor?,
'recent_abuse' => :recent_abuse?,
'bot_status' => :bot?,
'connection_type' => :connection_type,
'abuse_velocity' => :abuse_velocity,
'timezone' => :timezone,
}
end
key_method_mappings.each_pair do |key, meth|
define_method meth do
@data[key]
end
end
alias_method :state_code, :state
alias_method :country, :country_code
def postal_code
'' # No suitable fallback
end
def address
[city, state, country_code].compact.reject(&:empty?).join(', ')
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipinfo_io.rb | lib/geocoder/results/ipinfo_io.rb | require 'geocoder/results/base'
module Geocoder::Result
class IpinfoIo < Base
def address(format = :full)
"#{city} #{postal_code}, #{country}".sub(/^[ ,]*/, "")
end
def coordinates
@data['loc'].to_s.split(",").map(&:to_f)
end
def city
@data['city']
end
def state
@data['region']
end
def country
@data['country']
end
def postal_code
@data['postal']
end
def country_code
@data.fetch('country', '')
end
def state_code
@data.fetch('region_code', '')
end
def self.response_attributes
%w(ip region postal)
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/geocoder_ca.rb | lib/geocoder/results/geocoder_ca.rb | require 'geocoder/results/base'
module Geocoder::Result
class GeocoderCa < Base
def coordinates
[@data['latt'].to_f, @data['longt'].to_f]
end
def address(format = :full)
"#{street_address}, #{city}, #{state} #{postal_code}, #{country}".sub(/^[ ,]*/, "")
end
def street_address
"#{@data['stnumber']} #{@data['staddress']}"
end
def city
@data['city'] or (@data['standard'] and @data['standard']['city']) or ""
end
def state
@data['prov'] or (@data['standard'] and @data['standard']['prov']) or ""
end
alias_method :state_code, :state
def postal_code
@data['postal'] or (@data['standard'] and @data['standard']['postal']) or ""
end
def country
country_code == 'CA' ? 'Canada' : 'United States'
end
def country_code
return nil if state.nil? || state == ""
canadian_province_abbreviations.include?(state) ? "CA" : "US"
end
def self.response_attributes
%w[latt longt inlatt inlongt distance stnumber staddress prov
NearRoad NearRoadDistance betweenRoad1 betweenRoad2
intersection major_intersection]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
private # ----------------------------------------------------------------
def canadian_province_abbreviations
%w[ON QC NS NB MB BC PE SK AB NL]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/pointpin.rb | lib/geocoder/results/pointpin.rb | require 'geocoder/results/base'
module Geocoder::Result
class Pointpin < Base
def address
[ city_name, state, postal_code, country ].select{ |i| i.to_s != "" }.join(", ")
end
def city
@data['city_name']
end
def state
@data['region_name']
end
def state_code
@data['region_code']
end
def country
@data['country_name']
end
def postal_code
@data['postcode']
end
def self.response_attributes
%w[continent_code ip country_code country_name region_name city_name postcode latitude longitude time_zone languages]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/pdok_nl.rb | lib/geocoder/results/pdok_nl.rb | require 'geocoder/results/base'
module Geocoder::Result
class PdokNl < Base
def response_attributes
@data
end
def coordinates
@data['centroide_ll'][6..-2].split(' ').map(&:to_f).reverse
end
def formatted_address
@data['weergavenaam']
end
alias_method :address, :formatted_address
def province
@data['provincienaam']
end
alias_method :state, :province
def city
@data['woonplaatsnaam']
end
def district
@data['gemeentenaam']
end
def street
@data['straatnaam']
end
def street_number
@data['huis_nlt']
end
def address_components
@data
end
def state_code
@data['provinciecode']
end
def postal_code
@data['postcode']
end
def country
"Netherlands"
end
def country_code
"NL"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/tencent.rb | lib/geocoder/results/tencent.rb | require 'geocoder/results/base'
module Geocoder::Result
class Tencent < Base
def coordinates
['lat', 'lng'].map{ |i| @data['location'][i] }
end
def address
"#{province}#{city}#{district}#{street}#{street_number}"
#@data['title'] or @data['address']
end
# NOTE: The Tencent reverse geocoding API has the field named
# 'address_component' compared to 'address_components' in the
# regular geocoding API.
def province
@data['address_components'] and (@data['address_components']['province']) or
(@data['address_component'] and @data['address_component']['province']) or
""
end
alias_method :state, :province
def city
@data['address_components'] and (@data['address_components']['city']) or
(@data['address_component'] and @data['address_component']['city']) or
""
end
def district
@data['address_components'] and (@data['address_components']['district']) or
(@data['address_component'] and @data['address_component']['district']) or
""
end
def street
@data['address_components'] and (@data['address_components']['street']) or
(@data['address_component'] and @data['address_component']['street']) or
""
end
def street_number
@data['address_components'] and (@data['address_components']['street_number']) or
(@data['address_component'] and @data['address_component']['street_number']) or
""
end
def address_components
@data['address_components'] or @data['address_component']
end
def state_code
""
end
def postal_code
""
end
def country
"China"
end
def country_code
"CN"
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/pc_miler.rb | lib/geocoder/results/pc_miler.rb | require 'geocoder/results/base'
module Geocoder::Result
class PcMiler < Base
# sample response:
# https://singlesearch.alk.com/na/api/search?authToken=<TOKEN>&include=Meta&query=Feasterville
#
# {
# "Err": 0,
# "ErrString": "OK",
# "QueryConfidence": 1,
# "TimeInMilliseconds": 93,
# "GridDataVersion": "GRD_ALK.NA.2023.01.18.29.1.1",
# "CommitID": "pcmws-22.08.11.0-1778-g586da49bd1b: 05/30/2023 20:14",
# "Locations": [
# {
# "Address": {
# "StreetAddress": "",
# "LocalArea": "",
# "City": "Feasterville",
# "State": "PA",
# "StateName": "Pennsylvania",
# "Zip": "19053",
# "County": "Bucks",
# "Country": "US",
# "CountryFullName": "United States",
# "SPLC": null
# },
# "Coords": {
# "Lat": "40.150025",
# "Lon": "-75.002511"
# },
# "StreetCoords": {
# "Lat": "40.150098",
# "Lon": "-75.002827"
# },
# "Region": 4,
# "POITypeID": 0,
# "PersistentPOIID": -1,
# "SiteID": -1,
# "ResultType": 4,
# "ShortString": "Feasterville",
# "GridID": 37172748,
# "LinkID": 188,
# "Percent": 6291,
# "TimeZone": "GMT-4:00 EDT"
# }
# ]
# }
def address(format=:unused)
[street, city, state, postal_code, country]
.map { |i| i == '' ? nil : i }
.compact
.join(', ')
end
def coordinates
coords = data["Coords"] || {}
[coords["Lat"].to_f, coords["Lon"].to_f]
end
def street
address_data["StreetAddress"]
end
def city
address_data["City"]
end
def state
address_data["StateName"]
end
def state_code
address_data["State"]
end
def postal_code
address_data["Zip"]
end
def country
address_data["CountryFullName"]
end
def country_code
address_data["Country"]
end
private
def address_data
data["Address"] || {}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/google.rb | lib/geocoder/results/google.rb | require 'geocoder/results/base'
module Geocoder::Result
class Google < Base
def coordinates
['lat', 'lng'].map{ |i| geometry['location'][i] }
end
def address(format = :full)
formatted_address
end
def neighborhood
if neighborhood = address_components_of_type(:neighborhood).first
neighborhood['long_name']
end
end
def city
fields = [:locality, :sublocality,
:administrative_area_level_3,
:administrative_area_level_2]
fields.each do |f|
if entity = address_components_of_type(f).first
return entity['long_name']
end
end
return nil # no appropriate components found
end
def state
if state = address_components_of_type(:administrative_area_level_1).first
state['long_name']
end
end
def state_code
if state = address_components_of_type(:administrative_area_level_1).first
state['short_name']
end
end
def sub_state
if state = address_components_of_type(:administrative_area_level_2).first
state['long_name']
end
end
def sub_state_code
if state = address_components_of_type(:administrative_area_level_2).first
state['short_name']
end
end
def country
if country = address_components_of_type(:country).first
country['long_name']
end
end
def country_code
if country = address_components_of_type(:country).first
country['short_name']
end
end
def postal_code
if postal = address_components_of_type(:postal_code).first
postal['long_name']
end
end
def route
if route = address_components_of_type(:route).first
route['long_name']
end
end
def street_number
if street_number = address_components_of_type(:street_number).first
street_number['long_name']
end
end
def street_address
[street_number, route].compact.join(' ')
end
def types
@data['types']
end
def formatted_address
@data['formatted_address']
end
def address_components
@data['address_components']
end
##
# Get address components of a given type. Valid types are defined in
# Google's Geocoding API documentation and include (among others):
#
# :street_number
# :locality
# :neighborhood
# :route
# :postal_code
#
def address_components_of_type(type)
address_components.select{ |c| c['types'].include?(type.to_s) }
end
def geometry
@data['geometry']
end
def precision
geometry['location_type'] if geometry
end
def partial_match
@data['partial_match']
end
def place_id
@data['place_id']
end
def viewport
viewport = geometry['viewport'] || fail
bounding_box_from viewport
end
def bounds
bounding_box_from geometry['bounds']
end
private
def bounding_box_from(box)
return nil unless box
south, west = %w(lat lng).map { |c| box['southwest'][c] }
north, east = %w(lat lng).map { |c| box['northeast'][c] }
[south, west, north, east]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/db_ip_com.rb | lib/geocoder/results/db_ip_com.rb | require 'geocoder/results/base'
module Geocoder::Result
class DbIpCom < Base
def coordinates
['latitude', 'longitude'].map{ |coordinate_name| @data[coordinate_name] }
end
def city
@data['city']
end
def district
@data['district']
end
def state_code
@data['stateProvCode']
end
alias_method :state, :state_code
def zip_code
@data['zipCode']
end
alias_method :postal_code, :zip_code
def country_name
@data['countryName']
end
alias_method :country, :country_name
def country_code
@data['countryCode']
end
def continent_name
@data['continentName']
end
alias_method :continent, :continent_name
def continent_code
@data['continentCode']
end
def time_zone
@data['timeZone']
end
def gmt_offset
@data['gmtOffset']
end
def currency_code
@data['currencyCode']
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/google_places_details.rb | lib/geocoder/results/google_places_details.rb | require "geocoder/results/google"
module Geocoder
module Result
class GooglePlacesDetails < Google
def place_id
@data["place_id"]
end
def types
@data["types"] || []
end
def reviews
@data["reviews"] || []
end
def rating
@data["rating"]
end
def rating_count
@data["user_ratings_total"]
end
def phone_number
@data["international_phone_number"]
end
def website
@data["website"]
end
def photos
@data["photos"]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/google_places_search.rb | lib/geocoder/results/google_places_search.rb | require "geocoder/results/google"
module Geocoder
module Result
class GooglePlacesSearch < Google
def types
@data["types"] || []
end
def rating
@data["rating"]
end
def photos
@data["photos"]
end
def city
""
end
def state
""
end
def state_code
""
end
def province
""
end
def province_code
""
end
def postal_code
""
end
def country
""
end
def country_code
""
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/base.rb | lib/geocoder/results/base.rb | module Geocoder
module Result
class Base
# data (hash) fetched from geocoding service
attr_accessor :data
# true if result came from cache, false if from request to geocoding
# service; nil if cache is not configured
attr_accessor :cache_hit
##
# Takes a hash of data from a parsed geocoding service response.
#
def initialize(data)
@data = data
@cache_hit = nil
end
##
# A string in the given format.
#
# This default implementation dumbly follows the United States address
# format and will return incorrect results for most countries. Some APIs
# return properly formatted addresses and those should be funneled
# through this method.
#
def address(format = :full)
if state_code.to_s != ""
s = ", #{state_code}"
elsif state.to_s != ""
s = ", #{state}"
else
s = ""
end
"#{city}#{s} #{postal_code}, #{country}".sub(/^[ ,]*/, '')
end
##
# A two-element array: [lat, lon].
#
def coordinates
[@data['latitude'].to_f, @data['longitude'].to_f]
end
def latitude
coordinates[0]
end
def longitude
coordinates[1]
end
def state
fail
end
def province
state
end
def state_code
fail
end
def province_code
state_code
end
def country
fail
end
def country_code
fail
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/geoapify.rb | lib/geocoder/results/geoapify.rb | # frozen_string_literal: true
require 'geocoder/results/base'
module Geocoder
module Result
# https://apidocs.geoapify.com/docs/geocoding/api
class Geoapify < Base
def address(_format = :full)
properties['formatted']
end
def address_line1
properties['address_line1']
end
def address_line2
properties['address_line2']
end
def house_number
properties['housenumber']
end
def street
properties['street']
end
def postal_code
properties['postcode']
end
def district
properties['district']
end
def suburb
properties['suburb']
end
def city
properties['city']
end
def county
properties['county']
end
def state
properties['state']
end
def state_code
return '' unless properties['state_code']
properties['state_code'].upcase
end
def country
properties['country']
end
def country_code
return unless properties['country_code']
properties['country_code'].upcase
end
def coordinates
return unless properties['lat']
return unless properties['lon']
[properties['lat'], properties['lon']]
end
# See: https://tools.ietf.org/html/rfc7946#section-3.1
#
# Each feature has a "Point" type in the Geoapify API.
def geometry
return unless data['geometry']
symbol_hash data['geometry']
end
# See: https://tools.ietf.org/html/rfc7946#section-5
def bounds
data['bbox']
end
# Type of the result, one of:
#
# * :unknown
# * :amenity
# * :building
# * :street
# * :suburb
# * :district
# * :postcode
# * :city
# * :county
# * :state
# * :country
#
def type
return :unknown unless properties['result_type']
properties['result_type'].to_sym
end
# Distance in meters to given bias:proximity or to given coordinates for
# reverse geocoding
def distance
properties['distance']
end
# Calculated rank for the result, containing the following keys:
#
# * `popularity` - The popularity score of the result
# * `confidence` - The confidence value of the result (0-1)
# * `match_type` - The result's match type, one of following:
# * full_match
# * inner_part
# * match_by_building
# * match_by_street
# * match_by_postcode
# * match_by_city_or_disrict
# * match_by_country_or_state
#
# Example:
# {
# popularity: 8.615793062435909,
# confidence: 0.88,
# match_type: :full_match
# }
def rank
return unless properties['rank']
r = symbol_hash(properties['rank'])
r[:match_type] = r[:match_type].to_sym if r[:match_type]
r
end
# Examples:
#
# Open
# {
# sourcename: 'openstreetmap',
# wheelchair: 'limited',
# wikidata: 'Q186125',
# wikipedia: 'en:Madison Square Garden',
# website: 'http://www.thegarden.com/',
# phone: '12124656741',
# osm_type: 'W',
# osm_id: 138141251,
# continent: 'North America',
# }
def datasource
return unless properties['datasource']
symbol_hash properties['datasource']
end
private
def properties
@properties ||= data['properties'] || {}
end
def symbol_hash(orig_hash)
{}.tap do |result|
orig_hash.each_key do |key|
next unless orig_hash[key]
result[key.to_sym] = orig_hash[key]
end
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/nationaal_georegister_nl.rb | lib/geocoder/results/nationaal_georegister_nl.rb | require 'geocoder/results/base'
module Geocoder::Result
class NationaalGeoregisterNl < Base
def response_attributes
@data
end
def coordinates
@data['centroide_ll'][6..-2].split(' ').map(&:to_f).reverse
end
def formatted_address
@data['weergavenaam']
end
alias_method :address, :formatted_address
def province
@data['provincienaam']
end
alias_method :state, :province
def city
@data['woonplaatsnaam']
end
def district
@data['gemeentenaam']
end
def street
@data['straatnaam']
end
def street_number
@data['huis_nlt']
end
def address_components
@data
end
def state_code
@data['provinciecode']
end
def postal_code
@data['postcode']
end
def country
"Netherlands"
end
def country_code
"NL"
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/azure.rb | lib/geocoder/results/azure.rb | require 'geocoder/results/base'
module Geocoder::Result
class Azure < Base
def address
@data['address']['freeformAddress']
end
def building_number
@data['address']['buildingNumber']
end
def city
@data['address']['municipality']
end
def coordinates
if @data['position'].is_a?(String) # reverse geocoding result
@data['position'].split(',').map(&:to_f)
elsif @data['position'].is_a?(Hash) # forward geocoding result
[@data['position']['lat'], @data['position']['lon']]
end
end
def country
@data['address']['country']
end
def country_code
@data['address']['countryCode']
end
def district
@data['address']['municipalitySubdivision']
end
def postal_code
@data['address']['postalCode']
end
def province
@data['address']['countrySubdivision']
end
def state
@data['address']['countrySubdivision']
end
def state_code
@data['address']['countrySubdivisionCode']
end
def street_name
@data['address']['streetName']
end
def street_number
@data['address']['streetNumber']
end
def viewport
@data['viewport'] || {}
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/baidu.rb | lib/geocoder/results/baidu.rb | require 'geocoder/results/base'
module Geocoder::Result
class Baidu < Base
def coordinates
['lat', 'lng'].map{ |i| @data['location'][i] }
end
def province
@data['addressComponent'] and @data['addressComponent']['province'] or ""
end
alias_method :state, :province
def city
@data['addressComponent'] and @data['addressComponent']['city'] or ""
end
def district
@data['addressComponent'] and @data['addressComponent']['district'] or ""
end
def street
@data['addressComponent'] and @data['addressComponent']['street'] or ""
end
def street_number
@data['addressComponent'] and @data['addressComponent']['street_number']
end
def formatted_address
@data['formatted_address'] or ""
end
alias_method :address, :formatted_address
def address_components
@data['addressComponent']
end
def state_code
""
end
def postal_code
""
end
def country
"China"
end
def country_code
"CN"
end
##
# Get address components of a given type. Valid types are defined in
# Baidu's Geocoding API documentation and include (among others):
#
# :business
# :cityCode
#
def self.response_attributes
%w[business cityCode]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/opencagedata.rb | lib/geocoder/results/opencagedata.rb | require 'geocoder/results/base'
module Geocoder::Result
class Opencagedata < Base
def poi
%w[stadium bus_stop tram_stop].each do |key|
return @data['components'][key] if @data['components'].key?(key)
end
return nil
end
def house_number
@data['components']['house_number']
end
def address
@data['formatted']
end
def street
%w[road pedestrian highway].each do |key|
return @data['components'][key] if @data['components'].key?(key)
end
return nil
end
def city
%w[city town village hamlet].each do |key|
return @data['components'][key] if @data['components'].key?(key)
end
return nil
end
def village
@data['components']['village']
end
def state
@data['components']['state']
end
def state_code
@data['components']['state_code']
end
def postal_code
@data['components']['postcode'].to_s
end
def county
@data['components']['county']
end
def country
@data['components']['country']
end
def country_code
@data['components']['country_code']
end
def suburb
@data['components']['suburb']
end
def coordinates
[@data['geometry']['lat'].to_f, @data['geometry']['lng'].to_f]
end
def viewport
bounds = @data['bounds'] || fail
south, west = %w(lat lng).map { |i| bounds['southwest'][i] }
north, east = %w(lat lng).map { |i| bounds['northeast'][i] }
[south, west, north, east]
end
def time_zone
# The OpenCage API documentation states that `annotations` is available
# "when possible" https://geocoder.opencagedata.com/api#annotations
@data
.fetch('annotations', {})
.fetch('timezone', {})
.fetch('name', nil)
end
def self.response_attributes
%w[boundingbox license
formatted stadium]
end
response_attributes.each do |a|
unless method_defined?(a)
define_method a do
@data[a]
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/freegeoip.rb | lib/geocoder/results/freegeoip.rb | require 'geocoder/results/base'
module Geocoder::Result
class Freegeoip < Base
def city
@data['city']
end
def state
@data['region_name']
end
def state_code
@data['region_code']
end
def country
@data['country_name']
end
def country_code
@data['country_code']
end
def postal_code
@data['zipcode'] || @data['zip_code']
end
def self.response_attributes
%w[metro_code ip]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/pickpoint.rb | lib/geocoder/results/pickpoint.rb | require 'geocoder/results/nominatim'
module Geocoder::Result
class Pickpoint < Nominatim
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipinfo_io_lite.rb | lib/geocoder/results/ipinfo_io_lite.rb | require 'geocoder/results/base'
module Geocoder::Result
class IpinfoIoLite < Base
def self.response_attributes
%w(ip asn as_name as_domain country country_code continent continent_code)
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ip2location.rb | lib/geocoder/results/ip2location.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ip2location < Base
def address(format = :full)
"#{city_name} #{zip_code}, #{country_name}".sub(/^[ ,]*/, '')
end
def self.response_attributes
%w[country_code country_name region_name city_name latitude longitude
zip_code time_zone isp domain net_speed idd_code area_code usage_type
weather_station_code weather_station_name mcc mnc mobile_brand elevation]
end
response_attributes.each do |attr|
define_method attr do
@data[attr] || ""
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/mapbox.rb | lib/geocoder/results/mapbox.rb | require 'geocoder/results/base'
module Geocoder::Result
class Mapbox < Base
def coordinates
data['geometry']['coordinates'].reverse.map(&:to_f)
end
def place_name
data['place_name']
end
def street
data['properties']['address']
end
def city
data_part('place') || context_part('place')
end
def state
data_part('region') || context_part('region')
end
def state_code
if id_matches_name?(data['id'], 'region')
value = data['properties']['short_code']
else
value = context_part('region', 'short_code')
end
value.split('-').last unless value.nil?
end
def postal_code
data_part('postcode') || context_part('postcode')
end
def country
data_part('country') || context_part('country')
end
def country_code
if id_matches_name?(data['id'], 'country')
value = data['properties']['short_code']
else
value = context_part('country', 'short_code')
end
value.upcase unless value.nil?
end
def neighborhood
data_part('neighborhood') || context_part('neighborhood')
end
def address
data['place_name']
end
private
def id_matches_name?(id, name)
id =~ Regexp.new(name)
end
def data_part(name)
data['text'] if id_matches_name?(data['id'], name)
end
def context_part(name, key = 'text')
(context.detect { |c| id_matches_name?(c['id'], name) } || {})[key]
end
def context
Array(data['context'])
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ip2location_io.rb | lib/geocoder/results/ip2location_io.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ip2locationIo < Base
def address(format = :full)
"#{city_name} #{zip_code}, #{country_name}".sub(/^[ ,]*/, '')
end
def self.response_attributes
%w[ip country_code country_name region_name city_name latitude longitude
zip_code time_zone asn as is_proxy]
end
response_attributes.each do |attr|
define_method attr do
@data[attr] || ""
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/amap.rb | lib/geocoder/results/amap.rb | require 'geocoder/results/base'
module Geocoder::Result
class Amap < Base
def coordinates
location = @data['location'] || @data['roadinters'].try(:first).try(:[], 'location') \
|| address_components.try(:[], 'streetNumber').try(:[], 'location')
location.to_s.split(",").reverse.map(&:to_f)
end
def address
formatted_address
end
def state
province
end
def province
address_components['province']
end
def city
address_components['city'] == [] ? province : address_components["city"]
end
def district
address_components['district']
end
def street
if address_components["neighborhood"]["name"] != []
return address_components["neighborhood"]["name"]
elsif address_components['township'] != []
return address_components["township"]
else
return @data['street'] || address_components['streetNumber'].try(:[], 'street')
end
end
def street_number
@data['number'] || address_components['streetNumber'].try(:[], 'number')
end
def formatted_address
@data['formatted_address']
end
def address_components
@data['addressComponent'] || @data
end
def state_code
""
end
def postal_code
""
end
def country
"China"
end
def country_code
"CN"
end
##
# Get address components of a given type. Valid types are defined in
# Baidu's Geocoding API documentation and include (among others):
#
# :business
# :cityCode
#
def self.response_attributes
%w[roads pois roadinters]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/melissa_street.rb | lib/geocoder/results/melissa_street.rb | require 'geocoder/results/base'
module Geocoder::Result
class MelissaStreet < Base
def address(format = :full)
@data['FormattedAddress']
end
def street_address
@data['AddressLine1']
end
def suffix
@data['ThoroughfareTrailingType']
end
def number
@data['PremisesNumber']
end
def city
@data['Locality']
end
def state_code
@data['AdministrativeArea']
end
alias_method :state, :state_code
def country
@data['CountryName']
end
def country_code
@data['CountryISO3166_1_Alpha2']
end
def postal_code
@data['PostalCode']
end
def coordinates
[@data['Latitude'].to_f, @data['Longitude'].to_f]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/maxmind_geoip2.rb | lib/geocoder/results/maxmind_geoip2.rb | require 'geocoder/results/geoip2'
module Geocoder::Result
class MaxmindGeoip2 < Geoip2
# MindmindGeoip2 has the same results as Geoip2 because both are from MaxMind's GeoIP2 Precision Services
# See http://dev.maxmind.com/geoip/geoip2/web-services/ The difference being that Maxmind calls the service
# directly while GeoIP2 uses Hive::GeoIP2. See https://github.com/desuwa/hive_geoip2
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/postcode_anywhere_uk.rb | lib/geocoder/results/postcode_anywhere_uk.rb | require 'geocoder/results/base'
module Geocoder::Result
class PostcodeAnywhereUk < Base
def coordinates
[@data['Latitude'].to_f, @data['Longitude'].to_f]
end
def blank_result
''
end
alias_method :state, :blank_result
alias_method :state_code, :blank_result
alias_method :postal_code, :blank_result
def address
@data['Location']
end
def city
# is this too big a jump to assume that the API always
# returns a City, County as the last elements?
city = @data['Location'].split(',')[-2] || blank_result
city.strip
end
def os_grid
@data['OsGrid']
end
# This is a UK only API; all results are UK specific and
# so ommitted from API response.
def country
'United Kingdom'
end
def country_code
'UK'
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/postcodes_io.rb | lib/geocoder/results/postcodes_io.rb | require 'geocoder/results/base'
module Geocoder::Result
class PostcodesIo < Base
def coordinates
[@data['latitude'].to_f, @data['longitude'].to_f]
end
def quality
@data['quality']
end
def postal_code
@data['postcode']
end
alias address postal_code
def city
@data['admin_ward']
end
def county
@data['admin_county']
end
alias state county
def state_code
@data['codes']['admin_county']
end
def country
'United Kingdom'
end
def country_code
'UK'
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/here.rb | lib/geocoder/results/here.rb | require 'geocoder/results/base'
module Geocoder::Result
class Here < Base
##
# A string in the given format.
#
def address(format = :full)
address_data["label"]
end
##
# A two-element array: [lat, lon].
#
def coordinates
fail unless d = @data["position"]
[d["lat"].to_f, d["lng"].to_f]
end
def route
address_data["street"]
end
def street_number
address_data["houseNumber"]
end
def state
address_data["state"]
end
def province
address_data["county"]
end
def postal_code
address_data["postalCode"]
end
def city
address_data["city"]
end
def state_code
address_data["stateCode"]
end
def province_code
address_data["state"]
end
def country
address_data["countryName"]
end
def country_code
address_data["countryCode"]
end
def viewport
return [] if data["resultType"] == "place"
map_view = data["mapView"]
south = map_view["south"]
west = map_view["west"]
north = map_view["north"]
east = map_view["east"]
[south, west, north, east]
end
private # ----------------------------------------------------------------
def address_data
@data["address"] || fail
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/osmnames.rb | lib/geocoder/results/osmnames.rb | require 'geocoder/results/base'
module Geocoder::Result
class Osmnames < Base
def address
@data['display_name']
end
def coordinates
[@data['lat'].to_f, @data['lon'].to_f]
end
def viewport
west, south, east, north = @data['boundingbox'].map(&:to_f)
[south, west, north, east]
end
def state
@data['state']
end
alias_method :state_code, :state
def place_class
@data['class']
end
def place_type
@data['type']
end
def postal_code
''
end
def country_code
@data['country_code']
end
def country
@data['country']
end
def self.response_attributes
%w[house_number street city name osm_id osm_type boundingbox place_rank
importance county rank name_suffix]
end
response_attributes.each do |a|
unless method_defined?(a)
define_method a do
@data[a]
end
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipgeolocation.rb | lib/geocoder/results/ipgeolocation.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ipgeolocation < Base
def coordinates
[@data['latitude'].to_f, @data['longitude'].to_f]
end
def address(format = :full)
"#{city}, #{state} #{postal_code}, #{country_name}".sub(/^[ ,]*/, "")
end
def state
@data['state_prov']
end
def state_code
@data['state_prov']
end
def country
@data['country_name']
end
def country_code
@data['country_code2']
end
def postal_code
@data['zipcode']
end
def self.response_attributes
[
['ip', ''],
['hostname', ''],
['continent_code', ''],
['continent_name', ''],
['country_code2', ''],
['country_code3', ''],
['country_name', ''],
['country_capital',''],
['district',''],
['state_prov',''],
['city', ''],
['zipcode', ''],
['time_zone', {}],
['currency', {}]
]
end
response_attributes.each do |attr, default|
define_method attr do
@data[attr] || default
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/geoportail_lu.rb | lib/geocoder/results/geoportail_lu.rb | require 'geocoder/results/base'
module Geocoder::Result
class GeoportailLu < Base
def coordinates
geomlonlat['coordinates'].reverse if geolocalized?
end
def address
full_address
end
def city
try_to_extract 'locality', detailled_address
end
def state
'Luxembourg'
end
def state_code
'LU'
end
def postal_code
try_to_extract 'zip', detailled_address
end
def street_address
[street_number, street].compact.join(' ')
end
def street_number
try_to_extract 'postnumber', detailled_address
end
def street
try_to_extract 'street', detailled_address
end
def full_address
data['address']
end
def geomlonlat
data['geomlonlat']
end
def detailled_address
data['AddressDetails']
end
alias_method :country, :state
alias_method :province, :state
alias_method :country_code, :state_code
alias_method :province_code, :state_code
private
def geolocalized?
!!try_to_extract('coordinates', geomlonlat)
end
def try_to_extract(key, hash)
if hash.is_a?(Hash) and hash.include?(key)
hash[key]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/nominatim.rb | lib/geocoder/results/nominatim.rb | require 'geocoder/results/base'
module Geocoder::Result
class Nominatim < Base
def poi
return address_data[place_type] if address_data.key?(place_type)
return nil
end
def house_number
address_data['house_number']
end
def address
@data['display_name']
end
def street
%w[road pedestrian highway].each do |key|
return address_data[key] if address_data.key?(key)
end
return nil
end
def city
%w[city town village hamlet].each do |key|
return address_data[key] if address_data.key?(key)
end
return nil
end
def village
address_data['village']
end
def town
address_data['town']
end
def state
address_data['state']
end
alias_method :state_code, :state
def postal_code
address_data['postcode']
end
def county
address_data['county']
end
def country
address_data['country']
end
def country_code
address_data['country_code']
end
def suburb
address_data['suburb']
end
def city_district
address_data['city_district']
end
def state_district
address_data['state_district']
end
def neighbourhood
address_data['neighbourhood']
end
def municipality
address_data['municipality']
end
def coordinates
return [] unless @data['lat'] && @data['lon']
[@data['lat'].to_f, @data['lon'].to_f]
end
def place_class
@data['class']
end
def place_type
@data['type']
end
def viewport
south, north, west, east = @data['boundingbox'].map(&:to_f)
[south, west, north, east]
end
def self.response_attributes
%w[place_id osm_type osm_id boundingbox license
polygonpoints display_name class type stadium]
end
response_attributes.each do |a|
unless method_defined?(a)
define_method a do
@data[a]
end
end
end
private
def address_data
@data['address'] || {}
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/geoip2.rb | lib/geocoder/results/geoip2.rb | require 'geocoder/results/base'
module Geocoder
module Result
class Geoip2 < Base
def coordinates
%w[latitude longitude].map do |l|
data.fetch('location', {}).fetch(l, 0.0)
end
end
def city
fetch_name(
data.fetch('city', {}).fetch('names', {})
)
end
def state
fetch_name(
data.fetch('subdivisions', []).fetch(0, {}).fetch('names', {})
)
end
def state_code
data.fetch('subdivisions', []).fetch(0, {}).fetch('iso_code', '')
end
def country
fetch_name(
data.fetch('country', {}).fetch('names', {})
)
end
def country_code
data.fetch('country', {}).fetch('iso_code', '')
end
def postal_code
data.fetch('postal', {}).fetch('code', '')
end
def self.response_attributes
%w[ip]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
def language=(l)
@language = l.to_s
end
def language
@language ||= default_language
end
def data
@data.to_hash
end
private
def default_language
@default_language = Geocoder.config[:language].to_s
end
def fetch_name(names)
names[language] || names[default_language] || ''
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/pelias.rb | lib/geocoder/results/pelias.rb | require 'geocoder/results/base'
module Geocoder::Result
class Pelias < Base
def address(format = :full)
properties['label']
end
def city
locality
end
def coordinates
geometry['coordinates'].reverse
end
def country_code
properties['country_a']
end
def postal_code
properties['postalcode'].to_s
end
def province
state
end
def state
properties['region']
end
def state_code
properties['region_a']
end
def self.response_attributes
%w[county confidence country gid id layer localadmin locality neighborhood]
end
response_attributes.each do |a|
define_method a do
properties[a]
end
end
private
def geometry
@data.fetch('geometry', {})
end
def properties
@data.fetch('properties', {})
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/yandex.rb | lib/geocoder/results/yandex.rb | require 'geocoder/results/base'
module Geocoder::Result
class Yandex < Base
# Yandex result has difficult tree structure,
# and presence of some nodes depends on exact search case.
# Also Yandex lacks documentation about it.
# See https://tech.yandex.com/maps/doc/geocoder/desc/concepts/response_structure-docpage/
# Ultimatly, we need to find Locality and/or Thoroughfare data.
# It may resides on the top (ADDRESS_DETAILS) level.
# example: 'Baltic Sea'
# "AddressDetails": {
# "Locality": {
# "Premise": {
# "PremiseName": "Baltic Sea"
# }
# }
# }
ADDRESS_DETAILS = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails
].freeze
# On COUNTRY_LEVEL.
# example: 'Potomak'
# "AddressDetails": {
# "Country": {
# "AddressLine": "reka Potomak",
# "CountryNameCode": "US",
# "CountryName": "United States of America",
# "Locality": {
# "Premise": {
# "PremiseName": "reka Potomak"
# }
# }
# }
# }
COUNTRY_LEVEL = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails Country
].freeze
# On ADMIN_LEVEL (usually state or city)
# example: 'Moscow, Tverskaya'
# "AddressDetails": {
# "Country": {
# "AddressLine": "Moscow, Tverskaya Street",
# "CountryNameCode": "RU",
# "CountryName": "Russia",
# "AdministrativeArea": {
# "AdministrativeAreaName": "Moscow",
# "Locality": {
# "LocalityName": "Moscow",
# "Thoroughfare": {
# "ThoroughfareName": "Tverskaya Street"
# }
# }
# }
# }
# }
ADMIN_LEVEL = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails Country
AdministrativeArea
].freeze
# On SUBADMIN_LEVEL (may refer to urban district)
# example: 'Moscow Region, Krasnogorsk'
# "AddressDetails": {
# "Country": {
# "AddressLine": "Moscow Region, Krasnogorsk",
# "CountryNameCode": "RU",
# "CountryName": "Russia",
# "AdministrativeArea": {
# "AdministrativeAreaName": "Moscow Region",
# "SubAdministrativeArea": {
# "SubAdministrativeAreaName": "gorodskoy okrug Krasnogorsk",
# "Locality": {
# "LocalityName": "Krasnogorsk"
# }
# }
# }
# }
# }
SUBADMIN_LEVEL = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails Country
AdministrativeArea
SubAdministrativeArea
].freeze
# On DEPENDENT_LOCALITY_1 (may refer to district of city)
# example: 'Paris, Etienne Marcel'
# "AddressDetails": {
# "Country": {
# "AddressLine": "Île-de-France, Paris, 1er Arrondissement, Rue Étienne Marcel",
# "CountryNameCode": "FR",
# "CountryName": "France",
# "AdministrativeArea": {
# "AdministrativeAreaName": "Île-de-France",
# "Locality": {
# "LocalityName": "Paris",
# "DependentLocality": {
# "DependentLocalityName": "1er Arrondissement",
# "Thoroughfare": {
# "ThoroughfareName": "Rue Étienne Marcel"
# }
# }
# }
# }
# }
# }
DEPENDENT_LOCALITY_1 = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails Country
AdministrativeArea Locality
DependentLocality
].freeze
# On DEPENDENT_LOCALITY_2 (for special cases like turkish "mahalle")
# https://en.wikipedia.org/wiki/Mahalle
# example: 'Istanbul Mabeyinci Yokuşu 17'
# "AddressDetails": {
# "Country": {
# "AddressLine": "İstanbul, Fatih, Saraç İshak Mah., Mabeyinci Yokuşu, 17",
# "CountryNameCode": "TR",
# "CountryName": "Turkey",
# "AdministrativeArea": {
# "AdministrativeAreaName": "İstanbul",
# "SubAdministrativeArea": {
# "SubAdministrativeAreaName": "Fatih",
# "Locality": {
# "DependentLocality": {
# "DependentLocalityName": "Saraç İshak Mah.",
# "Thoroughfare": {
# "ThoroughfareName": "Mabeyinci Yokuşu",
# "Premise": {
# "PremiseNumber": "17"
# }
# }
# }
# }
# }
# }
# }
# }
DEPENDENT_LOCALITY_2 = %w[
GeoObject metaDataProperty GeocoderMetaData
AddressDetails Country
AdministrativeArea
SubAdministrativeArea Locality
DependentLocality
].freeze
def coordinates
@data['GeoObject']['Point']['pos'].split(' ').reverse.map(&:to_f)
end
def address(_format = :full)
@data['GeoObject']['metaDataProperty']['GeocoderMetaData']['text']
end
def city
result =
if state.empty?
find_in_hash(@data, *COUNTRY_LEVEL, 'Locality', 'LocalityName')
elsif sub_state.empty?
find_in_hash(@data, *ADMIN_LEVEL, 'Locality', 'LocalityName')
else
find_in_hash(@data, *SUBADMIN_LEVEL, 'Locality', 'LocalityName')
end
result || ""
end
def country
find_in_hash(@data, *COUNTRY_LEVEL, 'CountryName') || ""
end
def country_code
find_in_hash(@data, *COUNTRY_LEVEL, 'CountryNameCode') || ""
end
def state
find_in_hash(@data, *ADMIN_LEVEL, 'AdministrativeAreaName') || ""
end
def sub_state
return "" if state.empty?
find_in_hash(@data, *SUBADMIN_LEVEL, 'SubAdministrativeAreaName') || ""
end
def state_code
""
end
def street
thoroughfare_data.is_a?(Hash) ? thoroughfare_data['ThoroughfareName'] : ""
end
def street_number
premise.is_a?(Hash) ? premise.fetch('PremiseNumber', "") : ""
end
def premise_name
premise.is_a?(Hash) ? premise.fetch('PremiseName', "") : ""
end
def postal_code
return "" unless premise.is_a?(Hash)
find_in_hash(premise, 'PostalCode', 'PostalCodeNumber') || ""
end
def kind
@data['GeoObject']['metaDataProperty']['GeocoderMetaData']['kind']
end
def precision
@data['GeoObject']['metaDataProperty']['GeocoderMetaData']['precision']
end
def viewport
envelope = @data['GeoObject']['boundedBy']['Envelope'] || fail
east, north = envelope['upperCorner'].split(' ').map(&:to_f)
west, south = envelope['lowerCorner'].split(' ').map(&:to_f)
[south, west, north, east]
end
private # ----------------------------------------------------------------
def top_level_locality
find_in_hash(@data, *ADDRESS_DETAILS, 'Locality')
end
def country_level_locality
find_in_hash(@data, *COUNTRY_LEVEL, 'Locality')
end
def admin_locality
find_in_hash(@data, *ADMIN_LEVEL, 'Locality')
end
def subadmin_locality
find_in_hash(@data, *SUBADMIN_LEVEL, 'Locality')
end
def dependent_locality
find_in_hash(@data, *DEPENDENT_LOCALITY_1) ||
find_in_hash(@data, *DEPENDENT_LOCALITY_2)
end
def locality_data
dependent_locality || subadmin_locality || admin_locality ||
country_level_locality || top_level_locality
end
def thoroughfare_data
locality_data['Thoroughfare'] if locality_data.is_a?(Hash)
end
def premise
if thoroughfare_data.is_a?(Hash)
thoroughfare_data['Premise']
elsif locality_data.is_a?(Hash)
locality_data['Premise']
end
end
def find_in_hash(source, *keys)
key = keys.shift
result = source[key]
if keys.empty?
return result
elsif !result.is_a?(Hash)
return nil
end
find_in_hash(result, *keys)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/twogis.rb | lib/geocoder/results/twogis.rb | require 'geocoder/results/base'
module Geocoder::Result
class Twogis < Base
def coordinates
['lat', 'lon'].map{ |i| @data['point'][i] } if @data['point']
end
def address(_format = :full)
@data['full_address_name'] || ''
end
def city
return '' unless @data['adm_div']
@data['adm_div'].select{|u| u["type"] == "city"}.first.try(:[], 'name') || ''
end
def region
return '' unless @data['adm_div']
@data['adm_div'].select{|u| u["type"] == "region"}.first.try(:[], 'name') || ''
end
def country
return '' unless @data['adm_div']
@data['adm_div'].select{|u| u["type"] == "country"}.first.try(:[], 'name') || ''
end
def district
return '' unless @data['adm_div']
@data['adm_div'].select{|u| u["type"] == "district"}.first.try(:[], 'name') || ''
end
def district_area
return '' unless @data['adm_div']
@data['adm_div'].select{|u| u["type"] == "district_area"}.first.try(:[], 'name') || ''
end
def street_address
@data['address_name'] || ''
end
def street
return '' unless @data['address_name']
@data['address_name'].split(', ').first
end
def street_number
return '' unless @data['address_name']
@data['address_name'].split(', ')[1] || ''
end
def type
@data['type'] || ''
end
def purpose_name
@data['purpose_name'] || ''
end
def building_name
@data['building_name'] || ''
end
def subtype
@data['subtype'] || ''
end
def subtype_specification
@data['subtype_specification'] || ''
end
def name
@data['name'] || ''
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/esri.rb | lib/geocoder/results/esri.rb | require 'geocoder/results/base'
module Geocoder::Result
class Esri < Base
def address
address_key = reverse_geocode? ? 'Address' : 'Match_addr'
attributes[address_key]
end
def city
if !reverse_geocode? && is_city?
place_name
else
attributes['City']
end
end
def state
attributes['Region']
end
def state_code
abbr = attributes['RegionAbbr']
abbr.to_s == "" ? state : abbr
end
def country
country_key = reverse_geocode? ? "CountryCode" : "Country"
attributes[country_key]
end
alias_method :country_code, :country
def postal_code
attributes['Postal']
end
def place_name
place_name_key = reverse_geocode? ? "Address" : "PlaceName"
attributes[place_name_key]
end
def place_type
reverse_geocode? ? "Address" : attributes['Type']
end
def coordinates
[geometry["y"], geometry["x"]]
end
def viewport
north = attributes['Ymax']
south = attributes['Ymin']
east = attributes['Xmax']
west = attributes['Xmin']
[south, west, north, east]
end
private
def attributes
reverse_geocode? ? @data['address'] : @data['locations'].first['feature']['attributes']
end
def geometry
reverse_geocode? ? @data["location"] : @data['locations'].first['feature']["geometry"]
end
def reverse_geocode?
@data['locations'].nil?
end
def is_city?
['City', 'State Capital', 'National Capital'].include?(place_type)
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/location_iq.rb | lib/geocoder/results/location_iq.rb | require 'geocoder/results/nominatim'
module Geocoder::Result
class LocationIq < Nominatim
end
end | ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipbase.rb | lib/geocoder/results/ipbase.rb | require 'geocoder/results/base'
module Geocoder::Result
class Ipbase < Base
def ip
@data["data"]['ip']
end
def country_code
@data["data"]["location"]["country"]["alpha2"]
end
def country
@data["data"]["location"]["country"]["name"]
end
def state_code
@data["data"]["location"]["region"]["alpha2"]
end
def state
@data["data"]["location"]["region"]["name"]
end
def city
@data["data"]["location"]["city"]["name"]
end
def postal_code
@data["data"]["location"]["zip"]
end
def coordinates
[
@data["data"]["location"]["latitude"].to_f,
@data["data"]["location"]["longitude"].to_f
]
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/maxmind_local.rb | lib/geocoder/results/maxmind_local.rb | require 'geocoder/results/base'
module Geocoder::Result
class MaxmindLocal < Base
def coordinates
[@data[:latitude], @data[:longitude]]
end
def city
@data[:city_name]
end
def state
@data[:region_name]
end
def state_code
"" # Not available in Maxmind's database
end
def country
@data[:country_name]
end
def country_code
@data[:country_code2]
end
def postal_code
@data[:postal_code]
end
def self.response_attributes
%w[ip]
end
response_attributes.each do |a|
define_method a do
@data[a]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/baidu_ip.rb | lib/geocoder/results/baidu_ip.rb | require 'geocoder/results/base'
module Geocoder::Result
class BaiduIp < Base
def coordinates
[point['y'].to_f, point['x'].to_f]
end
def address
@data['address']
end
def state
province
end
def province
address_detail['province']
end
def city
address_detail['city']
end
def district
address_detail['district']
end
def street
address_detail['street']
end
def street_number
address_detail['street_number']
end
def state_code
""
end
def postal_code
""
end
def country
"China"
end
def country_code
"CN"
end
private
def address_detail
@data['address_detail']
end
def point
@data['point']
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
alexreisner/geocoder | https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder/results/ipapi_com.rb | lib/geocoder/results/ipapi_com.rb | require 'geocoder/results/base'
module Geocoder::Result
class IpapiCom < Base
def coordinates
[lat, lon]
end
def address
"#{city}, #{state_code} #{postal_code}, #{country}".sub(/^[ ,]*/, "")
end
def state
region_name
end
def state_code
region
end
def postal_code
zip
end
def country_code
@data['countryCode']
end
def region_name
@data['regionName']
end
def self.response_attributes
%w[country region city zip timezone isp org as reverse query status message mobile proxy lat lon]
end
response_attributes.each do |attribute|
define_method attribute do
@data[attribute]
end
end
end
end
| ruby | MIT | 8143fce1820539cdaf6344c3400edf5690ec1611 | 2026-01-04T15:40:27.673533Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman_spec.rb | spec/foreman_spec.rb | require "spec_helper"
require "foreman"
describe Foreman do
describe "VERSION" do
subject { Foreman::VERSION }
it { is_expected.to be_a String }
end
describe "runner" do
it "should exist" do
expect(File.exist?(Foreman.runner)).to eq(true)
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/helper_spec.rb | spec/helper_spec.rb | require "spec_helper"
describe "spec helpers" do
describe "#preserving_env" do
after { ENV.delete "FOO" }
it "should remove added environment vars" do
old = ENV["FOO"]
preserving_env { ENV["FOO"] = "baz" }
expect(ENV["FOO"]).to eq(old)
end
it "should reset modified environment vars" do
ENV["FOO"] = "bar"
preserving_env { ENV["FOO"] = "baz"}
expect(ENV["FOO"]).to eq("bar")
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/spec_helper.rb | spec/spec_helper.rb | require "simplecov"
SimpleCov.start do
add_filter "/spec/"
end
require "rspec"
require "timecop"
require "pp"
require "fakefs/safe"
require "fakefs/spec_helpers"
$:.unshift File.expand_path("../../lib", __FILE__)
def mock_export_error(message)
expect { yield }.to raise_error(Foreman::Export::Exception, message)
end
def mock_error(subject, message)
mock_exit do
expect(subject).to receive(:puts).with("ERROR: #{message}")
yield
end
end
def make_pipe
IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY")
end
def foreman(args)
capture_stdout do
begin
Foreman::CLI.start(args.split(" "))
rescue SystemExit
end
end
end
def forked_foreman(args)
rd, wr = make_pipe
Process.spawn("bundle exec bin/foreman #{args}", :out => wr, :err => wr)
wr.close
rd.read
end
def fork_and_capture(&blk)
rd, wr = make_pipe
pid = fork do
rd.close
wr.sync = true
$stdout.reopen wr
$stderr.reopen wr
blk.call
$stdout.flush
$stdout.close
end
wr.close
Process.wait pid
buffer = ""
until rd.eof?
buffer += rd.gets
end
end
def fork_and_get_exitstatus(args)
pid = Process.spawn("bundle exec bin/foreman #{args}", :out => "/dev/null", :err => "/dev/null")
Process.wait(pid)
$?.exitstatus
end
def mock_exit(&block)
expect { block.call }.to raise_error(SystemExit)
end
def write_foreman_config(app)
File.open("/etc/foreman/#{app}.conf", "w") do |file|
file.puts %{#{app}_processes="alpha bravo"}
file.puts %{#{app}_alpha="1"}
file.puts %{#{app}_bravo="2"}
end
end
def write_procfile(procfile="Procfile", alpha_env="")
FileUtils.mkdir_p(File.dirname(procfile))
File.open(procfile, "w") do |file|
file.puts "alpha: ./alpha" + " #{alpha_env}".rstrip
file.puts "\n"
file.puts "bravo:\t./bravo"
file.puts "foo_bar:\t./foo_bar"
file.puts "foo-bar:\t./foo-bar"
file.puts "# baz:\t./baz"
end
File.expand_path(procfile)
end
def write_file(file)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, 'w') do |f|
yield(f) if block_given?
end
end
def write_env(env=".env", options={"FOO"=>"bar"})
File.open(env, "w") do |file|
options.each do |key, val|
file.puts "#{key}=#{val}"
end
end
end
def without_fakefs
FakeFS.deactivate!
ret = yield
FakeFS.activate!
ret
end
def load_export_templates_into_fakefs(type)
without_fakefs do
Dir[File.expand_path("../../data/export/#{type}/**/*", __FILE__)].inject({}) do |hash, file|
next(hash) if File.directory?(file)
hash.update(file => File.read(file))
end
end.each do |filename, contents|
FileUtils.mkdir_p File.dirname(filename)
File.open(filename, "w") do |f|
f.puts contents
end
end
end
def resource_path(filename)
File.expand_path("../resources/#{filename}", __FILE__)
end
def example_export_file(filename)
FakeFS.deactivate!
data = File.read(File.expand_path(resource_path("export/#{filename}"), __FILE__))
FakeFS.activate!
data
end
def preserving_env
old_env = ENV.to_hash
begin
yield
ensure
ENV.clear
ENV.update(old_env)
end
end
def normalize_space(s)
s.gsub(/\n[\n\s]*/, "\n")
end
def capture_stdout
old_stdout = $stdout.dup
rd, wr = make_pipe
$stdout = wr
yield
wr.close
rd.read
ensure
$stdout = old_stdout
end
RSpec.configure do |config|
config.color = true
config.order = 'rand'
config.include FakeFS::SpecHelpers, :fakefs
config.before(:each) do
FileUtils.mkdir_p('/tmp')
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export_spec.rb | spec/foreman/export_spec.rb | require "spec_helper"
require "foreman/export"
describe "Foreman::Export" do
subject { Foreman::Export }
describe "with a formatter that doesn't declare the appropriate class" do
it "prints an error" do
expect(subject).to receive(:require).with("foreman/export/invalidformatter")
mock_export_error("Unknown export format: invalidformatter (no class Foreman::Export::Invalidformatter).") do
subject.formatter("invalidformatter")
end
end
end
describe "with an invalid formatter" do
it "prints an error" do
mock_export_error("Unknown export format: invalidformatter (unable to load file 'foreman/export/invalidformatter').") do
subject.formatter("invalidformatter")
end
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/procfile_spec.rb | spec/foreman/procfile_spec.rb | require 'spec_helper'
require 'foreman/procfile'
require 'pathname'
require 'tmpdir'
describe Foreman::Procfile, :fakefs do
subject { Foreman::Procfile.new }
it "can load from a file" do
write_procfile
subject.load "Procfile"
expect(subject["alpha"]).to eq("./alpha")
expect(subject["bravo"]).to eq("./bravo")
end
it "loads a passed-in Procfile" do
write_procfile
procfile = Foreman::Procfile.new("Procfile")
expect(procfile["alpha"]).to eq("./alpha")
expect(procfile["bravo"]).to eq("./bravo")
expect(procfile["foo-bar"]).to eq("./foo-bar")
expect(procfile["foo_bar"]).to eq("./foo_bar")
end
it "raises an error if Procfile is empty" do
write_file "Procfile" do |procfile|
procfile.puts
end
expect { Foreman::Procfile.new("Procfile") }.to raise_error described_class::EmptyFileError
end
it 'only creates Procfile entries for lines matching regex' do
write_procfile
procfile = Foreman::Procfile.new("Procfile")
keys = procfile.instance_variable_get(:@entries).map(&:first)
expect(keys).to match_array(%w[alpha bravo foo-bar foo_bar])
end
it "returns nil when attempting to retrieve an non-existing entry" do
write_procfile
procfile = Foreman::Procfile.new("Procfile")
expect(procfile["unicorn"]).to eq(nil)
end
it "can have a process appended to it" do
subject["charlie"] = "./charlie"
expect(subject["charlie"]).to eq("./charlie")
end
it "can write to a string" do
subject["foo"] = "./foo"
subject["bar"] = "./bar"
expect(subject.to_s).to eq("foo: ./foo\nbar: ./bar")
end
it "can write to a file" do
subject["foo"] = "./foo"
subject["bar"] = "./bar"
Dir.mkdir('/tmp')
subject.save "/tmp/proc"
expect(File.read("/tmp/proc")).to eq("foo: ./foo\nbar: ./bar\n")
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/cli_spec.rb | spec/foreman/cli_spec.rb | require "spec_helper"
require "foreman/cli"
describe "Foreman::CLI", :fakefs do
subject { Foreman::CLI.new }
describe ".foreman" do
before { File.open(".foreman", "w") { |f| f.puts "formation: alpha=2" } }
it "provides default options" do
expect(subject.send(:options)["formation"]).to eq("alpha=2")
end
it "is overridden by options at the cli" do
subject = Foreman::CLI.new([], :formation => "alpha=3")
expect(subject.send(:options)["formation"]).to eq("alpha=3")
end
end
describe "start" do
describe "when a Procfile doesnt exist", :fakefs do
it "displays an error" do
mock_error(subject, "Procfile does not exist.") do
expect_any_instance_of(Foreman::Engine).to_not receive(:start)
subject.start
end
end
end
describe "with a valid Procfile" do
it "can run a single command" do
without_fakefs do
output = foreman("start env -f #{resource_path("Procfile")}")
expect(output).to match(/env.1/)
expect(output).not_to match(/test.1/)
end
end
it "can run all commands" do
without_fakefs do
output = foreman("start -f #{resource_path("Procfile")} -e #{resource_path(".env")}")
expect(output).to match(/echo.1 \| echoing/)
expect(output).to match(/env.1 \| bar/)
expect(output).to match(/test.1 \| testing/)
end
end
it "sets PS variable with the process name" do
without_fakefs do
output = foreman("start -f #{resource_path("Procfile")}")
expect(output).to match(/ps.1 \| PS env var is ps.1/)
end
end
it "fails if process fails" do
output = `bundle exec foreman start -f #{resource_path "Procfile.bad"} && echo success`
expect(output).not_to include 'success'
end
end
end
describe "check" do
it "with a valid Procfile displays the jobs" do
write_procfile
expect(foreman("check")).to eq("valid procfile detected (alpha, bravo, foo_bar, foo-bar)\n")
end
it "with a blank Procfile displays an error" do
FileUtils.touch "Procfile"
expect(foreman("check")).to eq("ERROR: no processes defined\n")
end
it "without a Procfile displays an error" do
expect(foreman("check")).to eq("ERROR: Procfile does not exist.\n")
end
end
describe "run" do
it "can run a command" do
expect(forked_foreman("run -f #{resource_path("Procfile")} echo 1")).to eq("1\n")
end
it "doesn't parse options for the command" do
expect(forked_foreman("run -f #{resource_path("Procfile")} grep -e FOO #{resource_path(".env")}")).to eq("FOO=bar\n")
end
it "includes the environment" do
expect(forked_foreman("run -f #{resource_path("Procfile")} -e #{resource_path(".env")} #{resource_path("bin/env FOO")}")).to eq("bar\n")
end
it "can run a command from the Procfile" do
expect(forked_foreman("run -f #{resource_path("Procfile")} test")).to eq("testing\n")
end
it "exits with the same exit code as the command" do
expect(fork_and_get_exitstatus("run -f #{resource_path("Procfile")} echo 1")).to eq(0)
expect(fork_and_get_exitstatus("run -f #{resource_path("Procfile")} date 'invalid_date'")).to eq(1)
end
end
describe "version" do
it "displays gem version" do
expect(foreman("version").chomp).to eq(Foreman::VERSION)
end
it "displays gem version on shortcut command" do
expect(foreman("-v").chomp).to eq(Foreman::VERSION)
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/helpers_spec.rb | spec/foreman/helpers_spec.rb | require "spec_helper"
require "foreman/helpers"
describe "Foreman::Helpers" do
before do
module Foo
class Bar; end
end
end
after do
Object.send(:remove_const, :Foo)
end
subject { o = Object.new; o.extend(Foreman::Helpers); o }
it "should classify words" do
expect(subject.classify("foo")).to eq("Foo")
expect(subject.classify("foo-bar")).to eq("FooBar")
end
it "should constantize words" do
expect(subject.constantize("Object")).to eq(Object)
expect(subject.constantize("Foo::Bar")).to eq(Foo::Bar)
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/engine_spec.rb | spec/foreman/engine_spec.rb | require "spec_helper"
require "foreman/engine"
class Foreman::Engine::Tester < Foreman::Engine
attr_reader :buffer
def startup
@buffer = ""
end
def output(name, data)
@buffer += "#{name}: #{data}"
end
def shutdown
end
end
describe "Foreman::Engine", :fakefs do
subject do
write_procfile "Procfile"
Foreman::Engine::Tester.new.load_procfile("Procfile")
end
describe "initialize" do
describe "with a Procfile" do
before { write_procfile }
it "reads the processes" do
expect(subject.process("alpha").command).to eq("./alpha")
expect(subject.process("bravo").command).to eq("./bravo")
end
end
end
describe "start" do
it "forks the processes" do
expect(subject.process("alpha")).to receive(:run)
expect(subject.process("bravo")).to receive(:run)
expect(subject).to receive(:watch_for_output)
expect(subject).to receive(:wait_for_shutdown_or_child_termination)
subject.start
end
it "handles concurrency" do
subject.options[:formation] = "alpha=2"
expect(subject.process("alpha")).to receive(:run).twice
expect(subject.process("bravo")).to_not receive(:run)
expect(subject).to receive(:watch_for_output)
expect(subject).to receive(:wait_for_shutdown_or_child_termination)
subject.start
end
end
describe "directories" do
it "has the directory default relative to the Procfile" do
write_procfile "/some/app/Procfile"
engine = Foreman::Engine.new.load_procfile("/some/app/Procfile")
expect(engine.root).to eq("/some/app")
end
end
describe "environment" do
it "should read env files" do
write_file("/tmp/env") { |f| f.puts("FOO=baz") }
subject.load_env("/tmp/env")
expect(subject.env["FOO"]).to eq("baz")
end
it "should read more than one if specified" do
write_file("/tmp/env1") { |f| f.puts("FOO=bar") }
write_file("/tmp/env2") { |f| f.puts("BAZ=qux") }
subject.load_env "/tmp/env1"
subject.load_env "/tmp/env2"
expect(subject.env["FOO"]).to eq("bar")
expect(subject.env["BAZ"]).to eq("qux")
end
it "should handle quoted values" do
write_file("/tmp/env") do |f|
f.puts 'FOO=bar'
f.puts 'BAZ="qux"'
f.puts "FRED='barney'"
f.puts 'OTHER="escaped\"quote"'
f.puts 'URL="http://example.com/api?foo=bar&baz=1"'
end
subject.load_env "/tmp/env"
expect(subject.env["FOO"]).to eq("bar")
expect(subject.env["BAZ"]).to eq("qux")
expect(subject.env["FRED"]).to eq("barney")
expect(subject.env["OTHER"]).to eq('escaped"quote')
expect(subject.env["URL"]).to eq("http://example.com/api?foo=bar&baz=1")
end
it "should handle multiline strings" do
write_file("/tmp/env") do |f|
f.puts 'FOO="bar\nbaz"'
end
subject.load_env "/tmp/env"
expect(subject.env["FOO"]).to eq("bar\nbaz")
end
it "should fail if specified and doesnt exist" do
expect { subject.load_env "/tmp/env" }.to raise_error(Errno::ENOENT)
end
it "should set port from .env if specified" do
write_file("/tmp/env") { |f| f.puts("PORT=9000") }
subject.load_env "/tmp/env"
expect(subject.send(:base_port)).to eq(9000)
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/process_spec.rb | spec/foreman/process_spec.rb | require 'spec_helper'
require 'foreman/process'
require 'timeout'
require 'tmpdir'
describe Foreman::Process do
def run(process, options={})
rd, wr = IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY")
process.run(options.merge(:output => wr))
rd.gets
end
describe "#run" do
it "runs the process" do
process = Foreman::Process.new(resource_path("bin/test"))
expect(run(process)).to eq("testing\n")
end
it "can set environment" do
process = Foreman::Process.new(resource_path("bin/env FOO"), :env => { "FOO" => "bar" })
expect(run(process)).to eq("bar\n")
end
it "can set per-run environment" do
process = Foreman::Process.new(resource_path("bin/env FOO"))
expect(run(process, :env => { "FOO" => "bar "})).to eq("bar\n")
end
it "can handle env vars in the command" do
process = Foreman::Process.new(resource_path("bin/echo $FOO"), :env => { "FOO" => "bar" })
expect(run(process)).to eq("bar\n")
end
it "can handle per-run env vars in the command" do
process = Foreman::Process.new(resource_path("bin/echo $FOO"))
expect(run(process, :env => { "FOO" => "bar" })).to eq("bar\n")
end
it "should output utf8 properly" do
process = Foreman::Process.new(resource_path("bin/utf8"))
expect(run(process)).to eq(Foreman.ruby_18? ? "\xFF\x03\n" : "\xFF\x03\n".force_encoding('binary'))
end
it "can expand env in the command" do
process = Foreman::Process.new("command $FOO $BAR", :env => { "FOO" => "bar" })
expect(process.expanded_command).to eq("command bar $BAR")
end
it "can expand extra env in the command" do
process = Foreman::Process.new("command $FOO $BAR", :env => { "FOO" => "bar" })
expect(process.expanded_command("BAR" => "qux")).to eq("command bar qux")
end
it "can execute" do
expect(Kernel).to receive(:exec).with("bin/command")
process = Foreman::Process.new("bin/command")
process.exec
end
it "can execute with env" do
expect(Kernel).to receive(:exec).with("bin/command bar")
process = Foreman::Process.new("bin/command $FOO")
process.exec(:env => { "FOO" => "bar" })
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/supervisord_spec.rb | spec/foreman/export/supervisord_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/supervisord"
require "tmpdir"
describe Foreman::Export::Supervisord, :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:supervisord) { Foreman::Export::Supervisord.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("supervisord") }
before(:each) { allow(supervisord).to receive(:say) }
it "exports to the filesystem" do
write_env(".env", "FOO"=>"bar", "URL"=>"http://example.com/api?foo=bar&baz=1")
supervisord.engine.load_env('.env')
supervisord.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-1.conf"))
end
it "cleans up if exporting into an existing dir" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf")
supervisord.export
supervisord.export
end
context "with concurrency" do
let(:formation) { "alpha=2" }
it "exports to the filesystem with concurrency" do
supervisord.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-2.conf"))
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/upstart_spec.rb | spec/foreman/export/upstart_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/upstart"
require "tmpdir"
describe Foreman::Export::Upstart, :fakefs do
let(:procfile) { write_procfile("/tmp/app/Procfile") }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:upstart) { Foreman::Export::Upstart.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("upstart") }
before(:each) { allow(upstart).to receive(:say) }
it "exports to the filesystem" do
upstart.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf"))
expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf"))
expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf"))
expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("upstart/app-bravo.conf"))
expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("upstart/app-bravo-1.conf"))
end
it "cleans up if exporting into an existing dir" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar-1.conf")
upstart.export
upstart.export
end
it "does not delete exported files for similarly named applications" do
FileUtils.mkdir_p "/tmp/init"
["app2", "app2-alpha", "app2-alpha-1"].each do |name|
path = "/tmp/init/#{name}.conf"
FileUtils.touch(path)
expect(FileUtils).to_not receive(:rm).with(path)
end
upstart.export
end
it 'does not delete exported files for app which share name prefix' do
FileUtils.mkdir_p "/tmp/init"
["app-worker", "app-worker-worker", "app-worker-worker-1"].each do |name|
path = "/tmp/init/#{name}.conf"
FileUtils.touch(path)
expect(FileUtils).to_not receive(:rm).with(path)
end
upstart.export
expect(File.exist?('/tmp/init/app.conf')).to be true
expect(File.exist?('/tmp/init/app-worker.conf')).to be true
end
it "quotes and escapes environment variables" do
engine.env['KEY'] = 'd"\|d'
upstart.export
expect("foobarfoo").to include "bar"
expect(File.read("/tmp/init/app-alpha-1.conf")).to match(/KEY='d"\\\|d'/)
end
context "with a formation" do
let(:formation) { "alpha=2" }
it "exports to the filesystem with concurrency" do
upstart.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf"))
expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf"))
expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf"))
expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("upstart/app-alpha-2.conf"))
expect(File.exist?("/tmp/init/app-bravo-1.conf")).to eq(false)
end
end
context "with alternate templates" do
let(:template) { "/tmp/alternate" }
let(:options) { { :app => "app", :template => template } }
before do
FileUtils.mkdir_p template
File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" }
end
it "can export with alternate template files" do
upstart.export
expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n")
end
end
context "with alternate templates from home dir" do
before do
FileUtils.mkdir_p File.expand_path("~/.foreman/templates/upstart")
File.open(File.expand_path("~/.foreman/templates/upstart/master.conf.erb"), "w") do |file|
file.puts "default_alternate_template"
end
end
it "can export with alternate template files" do
upstart.export
expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n")
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/inittab_spec.rb | spec/foreman/export/inittab_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/inittab"
require "tmpdir"
describe Foreman::Export::Inittab, :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") }
let(:location) { "/tmp/inittab" }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:inittab) { Foreman::Export::Inittab.new(location, engine, options) }
before(:each) { load_export_templates_into_fakefs("inittab") }
before(:each) { allow(inittab).to receive(:say) }
it "exports to the filesystem" do
inittab.export
expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.default"))
end
context "to stdout" do
let(:location) { "-" }
it "exports to stdout" do
expect(inittab).to receive(:puts).with(example_export_file("inittab/inittab.default"))
inittab.export
end
end
context "with concurrency" do
let(:formation) { "alpha=2" }
it "exports to the filesystem with concurrency" do
inittab.export
expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.concurrency"))
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/daemon_spec.rb | spec/foreman/export/daemon_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/daemon"
require "tmpdir"
describe Foreman::Export::Daemon, :fakefs do
let(:procfile) { write_procfile("/tmp/app/Procfile") }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:daemon) { Foreman::Export::Daemon.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("daemon") }
before(:each) { allow(daemon).to receive(:say) }
it "exports to the filesystem" do
daemon.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf"))
expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf"))
expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf"))
expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("daemon/app-bravo.conf"))
expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("daemon/app-bravo-1.conf"))
end
it "cleans up if exporting into an existing dir" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar-1.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.conf")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar-1.conf")
daemon.export
daemon.export
end
it "does not delete exported files for similarly named applications" do
FileUtils.mkdir_p "/tmp/init"
["app2", "app2-alpha", "app2-alpha-1"].each do |name|
path = "/tmp/init/#{name}.conf"
FileUtils.touch(path)
expect(FileUtils).to_not receive(:rm).with(path)
end
daemon.export
end
context "with a formation" do
let(:formation) { "alpha=2" }
it "exports to the filesystem with concurrency" do
daemon.export
expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf"))
expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf"))
expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf"))
expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("daemon/app-alpha-2.conf"))
expect(File.exist?("/tmp/init/app-bravo-1.conf")).to eq(false)
end
end
context "with alternate templates" do
let(:template) { "/tmp/alternate" }
let(:options) { { :app => "app", :template => template } }
before do
FileUtils.mkdir_p template
File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" }
end
it "can export with alternate template files" do
daemon.export
expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n")
end
end
context "with alternate templates from home dir" do
before do
FileUtils.mkdir_p File.expand_path("~/.foreman/templates/daemon")
File.open(File.expand_path("~/.foreman/templates/daemon/master.conf.erb"), "w") do |file|
file.puts "default_alternate_template"
end
end
it "can export with alternate template files" do
daemon.export
expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n")
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/systemd_spec.rb | spec/foreman/export/systemd_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/systemd"
require "tmpdir"
describe Foreman::Export::Systemd, :fakefs, :aggregate_failures do
let(:procfile) { write_procfile("/tmp/app/Procfile") }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:systemd) { Foreman::Export::Systemd.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("systemd") }
before(:each) { allow(systemd).to receive(:say) }
it "exports to the filesystem" do
systemd.export
expect(File.read("/tmp/init/app.target")).to eq(example_export_file("systemd/app.target"))
expect(File.read("/tmp/init/app-alpha.1.service")).to eq(example_export_file("systemd/app-alpha.1.service"))
expect(File.read("/tmp/init/app-bravo.1.service")).to eq(example_export_file("systemd/app-bravo.1.service"))
end
context "when systemd export was run using the previous version of systemd export" do
before do
write_file("/tmp/init/app.target")
write_file("/tmp/init/app-alpha@.service")
write_file("/tmp/init/app-alpha.target")
write_file("/tmp/init/app-alpha.target.wants/app-alpha@5000.service")
write_file("/tmp/init/app-bravo.target")
write_file("/tmp/init/app-bravo@.service")
write_file("/tmp/init/app-bravo.target.wants/app-bravo@5100.service")
write_file("/tmp/init/app-foo_bar.target")
write_file("/tmp/init/app-foo_bar@.service")
write_file("/tmp/init/app-foo_bar.target.wants/app-foo_bar@5200.service")
write_file("/tmp/init/app-foo-bar.target")
write_file("/tmp/init/app-foo-bar@.service")
write_file("/tmp/init/app-foo-bar.target.wants/app-foo-bar@5300.service")
end
it "cleans up service files created by systemd export" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha@.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.target.wants/app-alpha@5000.service")
expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-alpha.target.wants")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo@.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.target.wants/app-bravo@5100.service")
expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-bravo.target.wants")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar@.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.target.wants/app-foo_bar@5200.service")
expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-foo_bar.target.wants")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar@.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.target.wants/app-foo-bar@5300.service")
expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-foo-bar.target.wants")
systemd.export
end
end
context "when systemd export was run using the current version of systemd export" do
before do
systemd.export
end
it "cleans up service files created by systemd export" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.target")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.1.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.1.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.1.service")
expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.1.service")
systemd.export
end
end
it "includes environment variables" do
engine.env['KEY'] = 'some "value"'
systemd.export
expect(File.read("/tmp/init/app-alpha.1.service")).to match(/KEY=some "value"/)
end
it "includes ExecStart line" do
engine.env['KEY'] = 'some "value"'
systemd.export
expect(File.read("/tmp/init/app-alpha.1.service")).to match(/^ExecStart=/)
end
context "with a custom formation specified" do
let(:formation) { "alpha=2" }
it "exports only those services that are specified in the formation" do
systemd.export
expect(File.read("/tmp/init/app.target")).to include("Wants=app-alpha.1.service app-alpha.2.service\n")
expect(File.read("/tmp/init/app-alpha.1.service")).to eq(example_export_file("systemd/app-alpha.1.service"))
expect(File.read("/tmp/init/app-alpha.2.service")).to eq(example_export_file("systemd/app-alpha.2.service"))
expect(File.exist?("/tmp/init/app-bravo.1.service")).to be_falsey
end
end
context "with alternate template directory specified" do
let(:template) { "/tmp/alternate" }
let(:options) { { :app => "app", :template => template } }
before do
FileUtils.mkdir_p template
File.open("#{template}/master.target.erb", "w") { |f| f.puts "alternate_template" }
end
it "uses template files found in the alternate directory" do
systemd.export
expect(File.read("/tmp/init/app.target")).to eq("alternate_template\n")
end
context "with alternate templates in the user home directory" do
before do
FileUtils.mkdir_p File.expand_path("~/.foreman/templates/systemd")
File.open(File.expand_path("~/.foreman/templates/systemd/master.target.erb"), "w") do |file|
file.puts "home_dir_template"
end
end
it "uses template files found in the alternate directory" do
systemd.export
expect(File.read("/tmp/init/app.target")).to eq("alternate_template\n")
end
end
end
context "with alternate templates in the user home directory" do
before do
FileUtils.mkdir_p File.expand_path("~/.foreman/templates/systemd")
File.open(File.expand_path("~/.foreman/templates/systemd/master.target.erb"), "w") do |file|
file.puts "home_dir_template"
end
end
it "uses template files found in the user home directory" do
systemd.export
expect(File.read("/tmp/init/app.target")).to eq("home_dir_template\n")
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/launchd_spec.rb | spec/foreman/export/launchd_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/launchd"
require "tmpdir"
describe Foreman::Export::Launchd, :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") }
let(:options) { Hash.new }
let(:engine) { Foreman::Engine.new().load_procfile(procfile) }
let(:launchd) { Foreman::Export::Launchd.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("launchd") }
before(:each) { allow(launchd).to receive(:say) }
it "exports to the filesystem" do
launchd.export
expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-a.default"))
expect(File.read("/tmp/init/app-bravo-1.plist")).to eq(example_export_file("launchd/launchd-b.default"))
end
context "with multiple command arguments" do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", "charlie") }
it "splits each command argument" do
launchd.export
expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-c.default"))
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/base_spec.rb | spec/foreman/export/base_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export"
describe "Foreman::Export::Base", :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") }
let(:location) { "/tmp/init" }
let(:engine) { Foreman::Engine.new().load_procfile(procfile) }
let(:subject) { Foreman::Export::Base.new(location, engine) }
it "has a say method for displaying info" do
expect(subject).to receive(:puts).with("[foreman export] foo")
subject.send(:say, "foo")
end
it "raises errors as a Foreman::Export::Exception" do
expect { subject.send(:error, "foo") }.to raise_error(Foreman::Export::Exception, "foo")
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/runit_spec.rb | spec/foreman/export/runit_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/runit"
require "tmpdir"
describe Foreman::Export::Runit, :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", 'bar=baz') }
let(:engine) { Foreman::Engine.new(:formation => "alpha=2,bravo=1").load_procfile(procfile) }
let(:options) { Hash.new }
let(:runit) { Foreman::Export::Runit.new('/tmp/init', engine, options) }
before(:each) { load_export_templates_into_fakefs("runit") }
before(:each) { allow(runit).to receive(:say) }
before(:each) { allow(FakeFS::FileUtils).to receive(:chmod) }
it "exports to the filesystem" do
engine.env["BAR"] = "baz"
runit.export
expect(File.read("/tmp/init/app-alpha-1/run")).to eq(example_export_file('runit/app-alpha-1/run'))
expect(File.read("/tmp/init/app-alpha-1/log/run")).to eq(example_export_file('runit/app-alpha-1/log/run'))
expect(File.read("/tmp/init/app-alpha-1/env/PORT")).to eq("5000\n")
expect(File.read("/tmp/init/app-alpha-1/env/BAR")).to eq("baz\n")
expect(File.read("/tmp/init/app-alpha-2/run")).to eq(example_export_file('runit/app-alpha-2/run'))
expect(File.read("/tmp/init/app-alpha-2/log/run")).to eq(example_export_file('runit/app-alpha-2/log/run'))
expect(File.read("/tmp/init/app-alpha-2/env/PORT")).to eq("5001\n")
expect(File.read("/tmp/init/app-alpha-2/env/BAR")).to eq("baz\n")
expect(File.read("/tmp/init/app-bravo-1/run")).to eq(example_export_file('runit/app-bravo-1/run'))
expect(File.read("/tmp/init/app-bravo-1/log/run")).to eq(example_export_file('runit/app-bravo-1/log/run'))
expect(File.read("/tmp/init/app-bravo-1/env/PORT")).to eq("5100\n")
end
it "creates a full path to the export directory" do
expect { runit.export }.to_not raise_error
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/spec/foreman/export/bluepill_spec.rb | spec/foreman/export/bluepill_spec.rb | require "spec_helper"
require "foreman/engine"
require "foreman/export/bluepill"
require "tmpdir"
describe Foreman::Export::Bluepill, :fakefs do
let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") }
let(:formation) { nil }
let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) }
let(:options) { Hash.new }
let(:bluepill) { Foreman::Export::Bluepill.new("/tmp/init", engine, options) }
before(:each) { load_export_templates_into_fakefs("bluepill") }
before(:each) { allow(bluepill).to receive(:say) }
it "exports to the filesystem" do
bluepill.export
expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app.pill")))
end
it "cleans up if exporting into an existing dir" do
expect(FileUtils).to receive(:rm).with("/tmp/init/app.pill")
bluepill.export
bluepill.export
end
context "with a process formation" do
let(:formation) { "alpha=2" }
it "exports to the filesystem with concurrency" do
bluepill.export
expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app-concurrency.pill")))
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman.rb | lib/foreman.rb | require "foreman/version"
module Foreman
def self.runner
File.expand_path("../../bin/foreman-runner", __FILE__)
end
def self.ruby_18?
defined?(RUBY_VERSION) and RUBY_VERSION =~ /^1\.8\.\d+/
end
def self.windows?
defined?(RUBY_PLATFORM) and RUBY_PLATFORM =~ /(win|w)32$/
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export.rb | lib/foreman/export.rb | require "foreman"
require "foreman/helpers"
require "pathname"
module Foreman::Export
extend Foreman::Helpers
class Exception < ::Exception; end
def self.formatter(format)
begin
require "foreman/export/#{ format.tr('-', '_') }"
classy_format = classify(format)
formatter = constantize("Foreman::Export::#{ classy_format }")
rescue NameError => ex
error "Unknown export format: #{format} (no class Foreman::Export::#{ classy_format })."
rescue LoadError => ex
error "Unknown export format: #{format} (unable to load file 'foreman/export/#{ format.tr('-', '_') }')."
end
end
def self.error(message)
raise Foreman::Export::Exception.new(message)
end
end
require "foreman/export/base"
require "foreman/export/inittab"
require "foreman/export/upstart"
require "foreman/export/daemon"
require "foreman/export/bluepill"
require "foreman/export/runit"
require "foreman/export/supervisord"
require "foreman/export/launchd"
require "foreman/export/systemd"
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/procfile.rb | lib/foreman/procfile.rb | require "foreman"
# Reads and writes Procfiles
#
# A valid Procfile entry is captured by this regex:
#
# /^([A-Za-z0-9_-]+):\s*(.+)$/
#
# All other lines are ignored.
#
class Foreman::Procfile
EmptyFileError = Class.new(StandardError)
# Initialize a Procfile
#
# @param [String] filename (nil) An optional filename to read from
#
def initialize(filename=nil)
@entries = []
load(filename) if filename
end
# Yield each +Procfile+ entry in order
#
def entries
@entries.each do |(name, command)|
yield name, command
end
end
# Retrieve a +Procfile+ command by name
#
# @param [String] name The name of the Procfile entry to retrieve
#
def [](name)
if entry = @entries.detect { |n,c| name == n }
entry.last
end
end
# Create a +Procfile+ entry
#
# @param [String] name The name of the +Procfile+ entry to create
# @param [String] command The command of the +Procfile+ entry to create
#
def []=(name, command)
delete name
@entries << [name, command]
end
# Remove a +Procfile+ entry
#
# @param [String] name The name of the +Procfile+ entry to remove
#
def delete(name)
@entries.reject! { |n,c| name == n }
end
# Load a Procfile from a file
#
# @param [String] filename The filename of the +Procfile+ to load
#
def load(filename)
parse_data = parse(filename)
raise EmptyFileError if parse_data.empty?
@entries.replace parse_data
end
# Save a Procfile to a file
#
# @param [String] filename Save the +Procfile+ to this file
#
def save(filename)
File.open(filename, 'w') do |file|
file.puts self.to_s
end
end
# Get the +Procfile+ as a +String+
#
def to_s
@entries.map do |name, command|
[ name, command ].join(": ")
end.join("\n")
end
private
def parse(filename)
File.read(filename).gsub("\r\n","\n").split("\n").map do |line|
if line =~ /^([A-Za-z0-9_-]+):\s*(.+)$/
[$1, $2]
end
end.compact
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/version.rb | lib/foreman/version.rb | module Foreman
VERSION = "0.90.0"
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/distribution.rb | lib/foreman/distribution.rb | module Foreman
module Distribution
def self.files
Dir[File.expand_path("../../../{bin,data,lib}/**/*", __FILE__)].select do |file|
File.file?(file)
end
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/env.rb | lib/foreman/env.rb | require "foreman"
class Foreman::Env
attr_reader :entries
def initialize(filename)
@entries = File.read(filename).gsub("\r\n","\n").split("\n").inject({}) do |ax, line|
if line =~ /\A([A-Za-z_0-9]+)=(.*)\z/
key = $1
case val = $2
# Remove single quotes
when /\A'(.*)'\z/ then ax[key] = $1
# Remove double quotes and unescape string preserving newline characters
when /\A"(.*)"\z/ then ax[key] = $1.gsub('\n', "\n").gsub(/\\(.)/, '\1')
else ax[key] = val
end
end
ax
end
end
def entries
@entries.each do |key, value|
yield key, value
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/helpers.rb | lib/foreman/helpers.rb | module Foreman::Helpers
# Copied whole sale from, https://github.com/defunkt/resque/
# Given a word with dashes, returns a camel cased version of it.
#
# classify('job-name') # => 'JobName'
def classify(dashed_word)
dashed_word.split('-').each { |part| part[0] = part[0].chr.upcase }.join
end # Tries to find a constant with the name specified in the argument string:
#
# constantize("Module") # => Module
# constantize("Test::Unit") # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# constantize("C") # => 'outside', same as ::C
# end
#
# NameError is raised when the constant is unknown.
def constantize(camel_cased_word)
camel_cased_word = camel_cased_word.to_s
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
args = Module.method(:const_get).arity != 1 ? [false] : []
if constant.const_defined?(name, *args)
constant = constant.const_get(name)
else
constant = constant.const_missing(name)
end
end
constant
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/process.rb | lib/foreman/process.rb | require "foreman"
require "shellwords"
class Foreman::Process
attr_reader :command
attr_reader :env
# Create a Process
#
# @param [String] command The command to run
# @param [Hash] options
#
# @option options [String] :cwd (./) Change to this working directory before executing the process
# @option options [Hash] :env ({}) Environment variables to set for this process
#
def initialize(command, options={})
@command = command
@options = options.dup
@options[:env] ||= {}
end
# Get environment-expanded command for a +Process+
#
# @param [Hash] custom_env ({}) Environment variables to merge with defaults
#
# @return [String] The expanded command
#
def expanded_command(custom_env={})
env = @options[:env].merge(custom_env)
expanded_command = command.dup
env.each do |key, val|
expanded_command.gsub!("$#{key}", val)
end
expanded_command
end
# Run a +Process+
#
# @param [Hash] options
#
# @option options :env ({}) Environment variables to set for this execution
# @option options :output ($stdout) The output stream
#
# @returns [Fixnum] pid The +pid+ of the process
#
def run(options={})
env = @options[:env].merge(options[:env] || {})
output = options[:output] || $stdout
runner = "#{Foreman.runner}".shellescape
Dir.chdir(cwd) do
Process.spawn env, expanded_command(env), :out => output, :err => output
end
end
# Exec a +Process+
#
# @param [Hash] options
#
# @option options :env ({}) Environment variables to set for this execution
#
# @return Does not return
def exec(options={})
env = @options[:env].merge(options[:env] || {})
env.each { |k, v| ENV[k] = v }
Dir.chdir(cwd)
Kernel.exec expanded_command(env)
end
# Returns the working directory for this +Process+
#
# @returns [String]
#
def cwd
File.expand_path(@options[:cwd] || ".")
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/cli.rb | lib/foreman/cli.rb | require "foreman"
require "foreman/helpers"
require "foreman/engine"
require "foreman/engine/cli"
require "foreman/export"
require "foreman/version"
require "shellwords"
require "thor"
require "yaml"
class Foreman::CLI < Thor
include Foreman::Helpers
map ["-v", "--version"] => :version
class_option :procfile, :type => :string, :aliases => "-f", :desc => "Default: Procfile"
class_option :root, :type => :string, :aliases => "-d", :desc => "Default: Procfile directory"
desc "start [PROCESS]", "Start the application (or a specific PROCESS)"
method_option :color, :type => :boolean, :aliases => "-c", :desc => "Force color to be enabled"
method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env"
method_option :formation, :type => :string, :aliases => "-m", :banner => '"alpha=5,bar=3"', :desc => 'Specify what processes will run and how many. Default: "all=1"'
method_option :port, :type => :numeric, :aliases => "-p"
method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5."
method_option :timestamp, :type => :boolean, :default => true, :desc => "Include timestamp in output"
class << self
def exit_on_failure?
true
end
# Hackery. Take the run method away from Thor so that we can redefine it.
def is_thor_reserved_word?(word, type)
return false if word == "run"
super
end
end
def start(process=nil)
check_procfile!
load_environment!
engine.load_procfile(procfile)
engine.options[:formation] = "#{process}=1" if process
engine.start
rescue Foreman::Procfile::EmptyFileError
error "no processes defined"
end
desc "export FORMAT LOCATION", "Export the application to another process management format"
method_option :app, :type => :string, :aliases => "-a"
method_option :log, :type => :string, :aliases => "-l"
method_option :run, :type => :string, :aliases => "-r", :desc => "Specify the pid file directory, defaults to /var/run/<application>"
method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env"
method_option :port, :type => :numeric, :aliases => "-p"
method_option :user, :type => :string, :aliases => "-u"
method_option :template, :type => :string, :aliases => "-t"
method_option :formation, :type => :string, :aliases => "-m", :banner => '"alpha=5,bar=3"', :desc => 'Specify what processes will run and how many. Default: "all=1"'
method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5."
def export(format, location=nil)
check_procfile!
load_environment!
engine.load_procfile(procfile)
formatter = Foreman::Export.formatter(format)
formatter.new(location, engine, options).export
rescue Foreman::Export::Exception, Foreman::Procfile::EmptyFileError => ex
error ex.message
end
desc "check", "Validate your application's Procfile"
def check
check_procfile!
engine.load_procfile(procfile)
puts "valid procfile detected (#{engine.process_names.join(', ')})"
rescue Foreman::Procfile::EmptyFileError
error "no processes defined"
end
desc "run COMMAND [ARGS...]", "Run a command using your application's environment"
method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env"
stop_on_unknown_option! :run
def run(*args)
load_environment!
if File.file?(procfile)
engine.load_procfile(procfile)
end
pid = fork do
begin
engine.env.each { |k,v| ENV[k] = v }
if args.size == 1 && process = engine.process(args.first)
process.exec(:env => engine.env)
else
exec args.shelljoin
end
rescue Errno::EACCES
error "not executable: #{args.first}"
rescue Errno::ENOENT
error "command not found: #{args.first}"
end
end
trap("INT") do
Process.kill(:INT, pid)
end
Process.wait(pid)
exit $?.exitstatus || 0
rescue Interrupt
rescue Foreman::Procfile::EmptyFileError
error "no processes defined"
end
desc "version", "Display Foreman gem version"
def version
puts Foreman::VERSION
end
no_tasks do
def engine
@engine ||= begin
engine_class = Foreman::Engine::CLI
engine = engine_class.new(options)
engine
end
end
def options
original_options = super
return original_options unless File.file?(".foreman")
defaults = ::YAML::load_file(".foreman") || {}
Thor::CoreExt::HashWithIndifferentAccess.new(defaults.merge(original_options))
end
end
private ######################################################################
def error(message)
puts "ERROR: #{message}"
exit 1
end
def check_procfile!
error("#{procfile} does not exist.") unless File.file?(procfile)
end
def load_environment!
if options[:env]
options[:env].split(",").each do |file|
engine.load_env file
end
else
default_env = File.join(engine.root, ".env")
engine.load_env default_env if File.file?(default_env)
end
end
def procfile
case
when options[:procfile] then options[:procfile]
when options[:root] then File.expand_path(File.join(options[:root], "Procfile"))
else "Procfile"
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/engine.rb | lib/foreman/engine.rb | require "foreman"
require "foreman/env"
require "foreman/process"
require "foreman/procfile"
require "tempfile"
require "fileutils"
require "thread"
class Foreman::Engine
# The signals that the engine cares about.
#
HANDLED_SIGNALS = [ :TERM, :INT, :HUP, :USR1, :USR2 ]
attr_reader :env
attr_reader :options
attr_reader :processes
# Create an +Engine+ for running processes
#
# @param [Hash] options
#
# @option options [String] :formation (all=1) The process formation to use
# @option options [Fixnum] :port (5000) The base port to assign to processes
# @option options [String] :root (Dir.pwd) The root directory from which to run processes
#
def initialize(options={})
@options = options.dup
@options[:formation] ||= "all=1"
@options[:timeout] ||= 5
@env = {}
@mutex = Mutex.new
@names = {}
@processes = []
@running = {}
@readers = {}
@shutdown = false
# Self-pipe for deferred signal-handling (ala djb: http://cr.yp.to/docs/selfpipe.html)
reader, writer = create_pipe
reader.close_on_exec = true if reader.respond_to?(:close_on_exec)
writer.close_on_exec = true if writer.respond_to?(:close_on_exec)
@selfpipe = { :reader => reader, :writer => writer }
# Set up a global signal queue
# http://blog.rubybestpractices.com/posts/ewong/016-Implementing-Signal-Handlers.html
Thread.main[:signal_queue] = []
end
# Start the processes registered to this +Engine+
#
def start
register_signal_handlers
startup
spawn_processes
watch_for_output
sleep 0.1
wait_for_shutdown_or_child_termination
shutdown
exit(@exitstatus) if @exitstatus
end
# Set up deferred signal handlers
#
def register_signal_handlers
HANDLED_SIGNALS.each do |sig|
if ::Signal.list.include? sig.to_s
trap(sig) { Thread.main[:signal_queue] << sig ; notice_signal }
end
end
end
# Unregister deferred signal handlers
#
def restore_default_signal_handlers
HANDLED_SIGNALS.each do |sig|
trap(sig, :DEFAULT) if ::Signal.list.include? sig.to_s
end
end
# Wake the main thread up via the selfpipe when there's a signal
#
def notice_signal
@selfpipe[:writer].write_nonblock( '.' )
rescue Errno::EAGAIN
# Ignore writes that would block
rescue Errno::EINTR
# Retry if another signal arrived while writing
retry
end
# Invoke the real handler for signal +sig+. This shouldn't be called directly
# by signal handlers, as it might invoke code which isn't re-entrant.
#
# @param [Symbol] sig the name of the signal to be handled
#
def handle_signal(sig)
case sig
when :TERM
handle_term_signal
when :INT
handle_interrupt
when :HUP
handle_hangup
when *HANDLED_SIGNALS
handle_signal_forward(sig)
else
system "unhandled signal #{sig}"
end
end
# Handle a TERM signal
#
def handle_term_signal
system "SIGTERM received, starting shutdown"
@shutdown = true
end
# Handle an INT signal
#
def handle_interrupt
system "SIGINT received, starting shutdown"
@shutdown = true
end
# Handle a HUP signal
#
def handle_hangup
system "SIGHUP received, starting shutdown"
@shutdown = true
end
def handle_signal_forward(signal)
system "#{signal} received, forwarding it to children"
kill_children signal
end
# Register a process to be run by this +Engine+
#
# @param [String] name A name for this process
# @param [String] command The command to run
# @param [Hash] options
#
# @option options [Hash] :env A custom environment for this process
#
def register(name, command, options={})
options[:env] ||= env
options[:cwd] ||= File.dirname(command.split(" ").first)
process = Foreman::Process.new(command, options)
@names[process] = name
@processes << process
end
# Clear the processes registered to this +Engine+
#
def clear
@names = {}
@processes = []
end
# Register processes by reading a Procfile
#
# @param [String] filename A Procfile from which to read processes to register
#
def load_procfile(filename)
options[:root] ||= File.dirname(filename)
Foreman::Procfile.new(filename).entries do |name, command|
register name, command, :cwd => options[:root]
end
self
end
# Load a .env file into the +env+ for this +Engine+
#
# @param [String] filename A .env file to load into the environment
#
def load_env(filename)
Foreman::Env.new(filename).entries do |name, value|
@env[name] = value
end
end
# Send a signal to all processes started by this +Engine+
#
# @param [String] signal The signal to send to each process
#
def kill_children(signal="SIGTERM")
if Foreman.windows?
@running.each do |pid, (process, index)|
system "sending #{signal} to #{name_for(pid)} at pid #{pid}"
begin
Process.kill(signal, pid)
rescue Errno::ESRCH, Errno::EPERM
end
end
else
begin
pids = @running.keys.compact
Process.kill signal, *pids unless pids.empty?
rescue Errno::ESRCH, Errno::EPERM
end
end
end
# Send a signal to the whole process group.
#
# @param [String] signal The signal to send
#
def killall(signal="SIGTERM")
if Foreman.windows?
kill_children(signal)
else
begin
Process.kill "-#{signal}", Process.pid
rescue Errno::ESRCH, Errno::EPERM
end
end
end
# Get the process formation
#
# @returns [Fixnum] The formation count for the specified process
#
def formation
@formation ||= parse_formation(options[:formation])
end
# List the available process names
#
# @returns [Array] A list of process names
#
def process_names
@processes.map { |p| @names[p] }
end
# Get the +Process+ for a specifid name
#
# @param [String] name The process name
#
# @returns [Foreman::Process] The +Process+ for the specified name
#
def process(name)
@names.invert[name]
end
# Yield each +Process+ in order
#
def each_process
process_names.each do |name|
yield name, process(name)
end
end
# Get the root directory for this +Engine+
#
# @returns [String] The root directory
#
def root
File.expand_path(options[:root] || Dir.pwd)
end
# Get the port for a given process and offset
#
# @param [Foreman::Process] process A +Process+ associated with this engine
# @param [Fixnum] instance The instance of the process
#
# @returns [Fixnum] port The port to use for this instance of this process
#
def port_for(process, instance, base=nil)
if base
base + (@processes.index(process.process) * 100) + (instance - 1)
else
base_port + (@processes.index(process) * 100) + (instance - 1)
end
end
# Get the base port for this foreman instance
#
# @returns [Fixnum] port The base port
#
def base_port
(options[:port] || env["PORT"] || ENV["PORT"] || 5000).to_i
end
# deprecated
def environment
env
end
private
### Engine API ######################################################
def startup
raise TypeError, "must use a subclass of Foreman::Engine"
end
def output(name, data)
raise TypeError, "must use a subclass of Foreman::Engine"
end
def shutdown
raise TypeError, "must use a subclass of Foreman::Engine"
end
## Helpers ##########################################################
def create_pipe
IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY")
end
def name_for(pid)
process, index = @running[pid]
name_for_index(process, index)
end
def name_for_index(process, index)
[ @names[process], index.to_s ].compact.join(".")
end
def parse_formation(formation)
pairs = formation.to_s.gsub(/\s/, "").split(",")
pairs.inject(Hash.new(0)) do |ax, pair|
process, amount = pair.split("=")
process == "all" ? ax.default = amount.to_i : ax[process] = amount.to_i
ax
end
end
def output_with_mutex(name, message)
@mutex.synchronize do
output name, message
end
end
def system(message)
output_with_mutex "system", message
end
def termination_message_for(status)
if status.exited?
"exited with code #{status.exitstatus}"
elsif status.signaled?
"terminated by SIG#{Signal.list.invert[status.termsig]}"
else
"died a mysterious death"
end
end
def flush_reader(reader)
until reader.eof?
data = reader.gets
output_with_mutex name_for(@readers.key(reader)), data
end
end
## Engine ###########################################################
def spawn_processes
@processes.each do |process|
1.upto(formation[@names[process]]) do |n|
reader, writer = create_pipe
begin
pid = process.run(:output => writer, :env => {
"PORT" => port_for(process, n).to_s,
"PS" => name_for_index(process, n)
})
writer.puts "started with pid #{pid}"
rescue Errno::ENOENT
writer.puts "unknown command: #{process.command}"
end
@running[pid] = [process, n]
@readers[pid] = reader
end
end
end
def read_self_pipe
@selfpipe[:reader].read_nonblock(11)
rescue Errno::EAGAIN, Errno::EINTR, Errno::EBADF, Errno::EWOULDBLOCK
# ignore
end
def handle_signals
while sig = Thread.main[:signal_queue].shift
self.handle_signal(sig)
end
end
def handle_io(readers)
readers.each do |reader|
next if reader == @selfpipe[:reader]
if reader.eof?
@readers.delete_if { |key, value| value == reader }
else
data = reader.gets
output_with_mutex name_for(@readers.invert[reader]), data
end
end
end
def watch_for_output
Thread.new do
begin
loop do
io = IO.select([@selfpipe[:reader]] + @readers.values, nil, nil, 30)
read_self_pipe
handle_signals
handle_io(io ? io.first : [])
end
rescue Exception => ex
puts ex.message
puts ex.backtrace
end
end
end
def wait_for_shutdown_or_child_termination
loop do
# Stop if it is time to shut down (asked via a signal)
break if @shutdown
# Stop if any of the children died
break if check_for_termination
# Sleep for a moment and do not blow up if any signals are coming our way
begin
sleep(1)
rescue Exception
# noop
end
end
# Ok, we have exited from the main loop, time to shut down gracefully
terminate_gracefully
end
def check_for_termination
# Check if any of the children have died off
pid, status = begin
Process.wait2(-1, Process::WNOHANG)
rescue Errno::ECHILD
return nil
end
# record the exit status
@exitstatus ||= status.exitstatus if status
# If no childred have died, nothing to do here
return nil unless pid
# Log the information about the process that exited
output_with_mutex name_for(pid), termination_message_for(status)
# Delete it from the list of running processes and return its pid
@running.delete(pid)
return pid
end
def terminate_gracefully
restore_default_signal_handlers
# Tell all children to stop gracefully
if Foreman.windows?
system "sending SIGKILL to all processes"
kill_children "SIGKILL"
else
system "sending SIGTERM to all processes"
kill_children "SIGTERM"
end
# Wait for all children to stop or until the time comes to kill them all
start_time = Time.now
while Time.now - start_time <= options[:timeout]
return if @running.empty?
check_for_termination
# Sleep for a moment and do not blow up if more signals are coming our way
begin
sleep(0.1)
rescue Exception
# noop
end
end
# Ok, we have no other option than to kill all of our children
system "sending SIGKILL to all processes"
kill_children "SIGKILL"
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/bluepill.rb | lib/foreman/export/bluepill.rb | require "erb"
require "foreman/export"
class Foreman::Export::Bluepill < Foreman::Export::Base
def export
super
clean "#{location}/#{app}.pill"
write_template "bluepill/master.pill.erb", "#{app}.pill", binding
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/daemon.rb | lib/foreman/export/daemon.rb | require "erb"
require "foreman/export"
class Foreman::Export::Daemon < Foreman::Export::Base
def export
super
(Dir["#{location}/#{app}-*.conf"] << "#{location}/#{app}.conf").each do |file|
clean file
end
write_template "daemon/master.conf.erb", "#{app}.conf", binding
engine.each_process do |name, process|
next if engine.formation[name] < 1
write_template "daemon/process_master.conf.erb", "#{app}-#{name}.conf", binding
1.upto(engine.formation[name]) do |num|
port = engine.port_for(process, num)
arguments = process.command.split(" ")
executable = arguments.slice!(0)
arguments = arguments.size > 0 ? " -- #{arguments.join(' ')}" : ""
write_template "daemon/process.conf.erb", "#{app}-#{name}-#{num}.conf", binding
end
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/systemd.rb | lib/foreman/export/systemd.rb | require "erb"
require "foreman/export"
class Foreman::Export::Systemd < Foreman::Export::Base
def export
super
Dir["#{location}/#{app}*.target"]
.concat(Dir["#{location}/#{app}*.service"])
.concat(Dir["#{location}/#{app}*.target.wants/#{app}*.service"])
.each do |file|
clean file
end
Dir["#{location}/#{app}*.target.wants"].each do |file|
clean_dir file
end
service_names = []
engine.each_process do |name, process|
1.upto(engine.formation[name]) do |num|
port = engine.port_for(process, num)
process_name = "#{name}.#{num}"
service_filename = "#{app}-#{process_name}.service"
write_template "systemd/process.service.erb", service_filename, binding
service_names << service_filename
end
end
write_template "systemd/master.target.erb", "#{app}.target", binding
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/base.rb | lib/foreman/export/base.rb | require "foreman/export"
require "pathname"
require "shellwords"
class Foreman::Export::Base
attr_reader :location
attr_reader :engine
attr_reader :options
attr_reader :formation
# deprecated
attr_reader :port
def initialize(location, engine, options={})
@location = location
@engine = engine
@options = options.dup
@formation = engine.formation
end
def export
error("Must specify a location") unless location
FileUtils.mkdir_p(location) rescue error("Could not create: #{location}")
chown user, log
chown user, run
end
def app
options[:app] || "app"
end
def log
options[:log] || "/var/log/#{app}"
end
def run
options[:run] || "/var/run/#{app}"
end
def user
options[:user] || app
end
private ######################################################################
def chown user, dir
FileUtils.chown user, nil, dir
rescue
error("Could not chown #{dir} to #{user}") unless File.writable?(dir) || ! File.exist?(dir)
end
def error(message)
raise Foreman::Export::Exception.new(message)
end
def say(message)
puts "[foreman export] %s" % message
end
def clean(filename)
return unless File.exist?(filename)
say "cleaning up: #{filename}"
FileUtils.rm(filename)
end
def clean_dir(dirname)
return unless File.exist?(dirname)
say "cleaning up directory: #{dirname}"
FileUtils.rm_r(dirname)
end
def shell_quote(value)
Shellwords.escape(value)
end
# deprecated
def old_export_template(exporter, file, template_root)
if template_root && File.exist?(file_path = File.join(template_root, file))
File.read(file_path)
elsif File.exist?(file_path = File.expand_path(File.join("~/.foreman/templates", file)))
File.read(file_path)
else
File.read(File.expand_path("../../../../data/export/#{exporter}/#{file}", __FILE__))
end
end
def export_template(name, file=nil, template_root=nil)
if file && template_root
old_export_template name, file, template_root
else
name_without_first = name.split("/")[1..-1].join("/")
matchers = []
matchers << File.join(options[:template], name_without_first) if options[:template]
matchers << File.expand_path("~/.foreman/templates/#{name}")
matchers << File.expand_path("../../../../data/export/#{name}", __FILE__)
File.read(matchers.detect { |m| File.exist?(m) })
end
end
def write_template(name, target, binding)
compiled = if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
ERB.new(export_template(name), trim_mode: '-').result(binding)
else
ERB.new(export_template(name), nil, '-').result(binding)
end
write_file target, compiled
end
def chmod(mode, file)
say "setting #{file} to mode #{mode}"
FileUtils.chmod mode, File.join(location, file)
end
def create_directory(dir)
say "creating: #{dir}"
FileUtils.mkdir_p(File.join(location, dir))
end
def create_symlink(link, target)
say "symlinking: #{link} -> #{target}"
FileUtils.symlink(target, File.join(location, link))
end
def write_file(filename, contents)
say "writing: #{filename}"
filename = File.join(location, filename) unless Pathname.new(filename).absolute?
File.open(filename, "w") do |file|
file.puts contents
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/supervisord.rb | lib/foreman/export/supervisord.rb | require "erb"
require "foreman/export"
class Foreman::Export::Supervisord < Foreman::Export::Base
def export
super
Dir["#{location}/#{app}.conf"].each do |file|
clean file
end
write_template "supervisord/app.conf.erb", "#{app}.conf", binding
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/launchd.rb | lib/foreman/export/launchd.rb | require "erb"
require "foreman/export"
class Foreman::Export::Launchd < Foreman::Export::Base
def export
super
engine.each_process do |name, process|
1.upto(engine.formation[name]) do |num|
port = engine.port_for(process, num)
command_args = process.command.split(/\s+/).map{|arg|
case arg
when "$PORT" then port
else arg
end
}
write_template "launchd/launchd.plist.erb", "#{app}-#{name}-#{num}.plist", binding
end
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/upstart.rb | lib/foreman/export/upstart.rb | require "erb"
require "foreman/export"
class Foreman::Export::Upstart < Foreman::Export::Base
def export
super
master_file = "#{app}.conf"
clean File.join(location, master_file)
write_template master_template, master_file, binding
engine.each_process do |name, process|
process_master_file = "#{app}-#{name}.conf"
process_file = "#{app}-#{name}-%s.conf"
Dir[
File.join(location, process_master_file),
File.join(location, process_file % "*")
].each { |f| clean(f) }
next if engine.formation[name] < 1
write_template process_master_template, process_master_file, binding
1.upto(engine.formation[name]) do |num|
port = engine.port_for(process, num)
write_template process_template, process_file % num, binding
end
end
end
private
def master_template
"upstart/master.conf.erb"
end
def process_master_template
"upstart/process_master.conf.erb"
end
def process_template
"upstart/process.conf.erb"
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/inittab.rb | lib/foreman/export/inittab.rb | require "foreman/export"
class Foreman::Export::Inittab < Foreman::Export::Base
def export
error("Must specify a location") unless location
inittab = []
inittab << "# ----- foreman #{app} processes -----"
index = 1
engine.each_process do |name, process|
1.upto(engine.formation[name]) do |num|
id = app.slice(0, 2).upcase + sprintf("%02d", index)
port = engine.port_for(process, num)
commands = []
commands << "cd #{engine.root}"
commands << "export PORT=#{port}"
engine.env.each_pair do |var, env|
commands << "export #{var.upcase}=#{shell_quote(env)}"
end
commands << "#{process.command} >> #{log}/#{name}-#{num}.log 2>&1"
inittab << "#{id}:4:respawn:/bin/su - #{user} -c '#{commands.join(";")}'"
index += 1
end
end
inittab << "# ----- end foreman #{app} processes -----"
inittab = inittab.join("\n") + "\n"
if location == "-"
puts inittab
else
say "writing: #{location}"
File.open(location, "w") { |file| file.puts inittab }
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/export/runit.rb | lib/foreman/export/runit.rb | require "erb"
require "foreman/export"
class Foreman::Export::Runit < Foreman::Export::Base
ENV_VARIABLE_REGEX = /([a-zA-Z_]+[a-zA-Z0-9_]*)=(\S+)/
def export
super
engine.each_process do |name, process|
1.upto(engine.formation[name]) do |num|
process_directory = "#{app}-#{name}-#{num}"
create_directory process_directory
create_directory "#{process_directory}/env"
create_directory "#{process_directory}/log"
write_template "runit/run.erb", "#{process_directory}/run", binding
chmod 0755, "#{process_directory}/run"
port = engine.port_for(process, num)
engine.env.merge("PORT" => port.to_s).each do |key, value|
write_file "#{process_directory}/env/#{key}", value
end
write_template "runit/log/run.erb", "#{process_directory}/log/run", binding
chmod 0755, "#{process_directory}/log/run"
end
end
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
ddollar/foreman | https://github.com/ddollar/foreman/blob/f65ddba83932bd4670e014389d6e27ea1e20b469/lib/foreman/engine/cli.rb | lib/foreman/engine/cli.rb | require "foreman/engine"
class Foreman::Engine::CLI < Foreman::Engine
module Color
ANSI = {
:reset => 0,
:black => 30,
:red => 31,
:green => 32,
:yellow => 33,
:blue => 34,
:magenta => 35,
:cyan => 36,
:white => 37,
:bright_black => 30,
:bright_red => 31,
:bright_green => 32,
:bright_yellow => 33,
:bright_blue => 34,
:bright_magenta => 35,
:bright_cyan => 36,
:bright_white => 37,
}
def self.enable(io, force=false)
io.extend(self)
@@color_force = force
end
def color?
return true if @@color_force
return false if Foreman.windows?
return false unless self.respond_to?(:isatty)
self.isatty && ENV["TERM"]
end
def color(name)
return "" unless color?
return "" unless ansi = ANSI[name.to_sym]
"\e[#{ansi}m"
end
end
FOREMAN_COLORS = %w( cyan yellow green magenta red blue bright_cyan bright_yellow
bright_green bright_magenta bright_red bright_blue )
def startup
@colors = map_colors
proctitle "foreman: main" unless Foreman.windows?
Color.enable($stdout, options[:color])
end
def output(name, data)
data.to_s.lines.map(&:chomp).each do |message|
output = ""
output += $stdout.color(@colors[name.split(".").first].to_sym)
output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp]
output += "#{pad_process_name(name)} | "
output += $stdout.color(:reset)
output += message
$stdout.puts output
$stdout.flush
end
rescue Errno::EPIPE
terminate_gracefully
end
def shutdown
end
private
def name_padding
@name_padding ||= begin
index_padding = @names.values.map { |n| formation[n] }.max.to_s.length + 1
name_padding = @names.values.map { |n| n.length + index_padding }.sort.last
[ 6, name_padding.to_i ].max
end
end
def pad_process_name(name)
name.ljust(name_padding, " ")
end
def map_colors
colors = Hash.new("white")
@names.values.each_with_index do |name, index|
colors[name] = FOREMAN_COLORS[index % FOREMAN_COLORS.length]
end
colors["system"] = "bright_white"
colors
end
def proctitle(title)
$0 = title
end
def termtitle(title)
printf("\033]0;#{title}\007") unless Foreman.windows?
end
end
| ruby | MIT | f65ddba83932bd4670e014389d6e27ea1e20b469 | 2026-01-04T15:40:56.223088Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/test/markup_test.rb | test/markup_test.rb | # encoding: utf-8
$LOAD_PATH.unshift File.dirname(__FILE__) + "/../lib"
require 'github/markup'
require 'minitest/autorun'
require 'html/pipeline'
require 'nokogiri'
require 'nokogiri/diff'
def normalize_html(text)
text.strip
.gsub(/\s\s+/,' ')
.gsub(/\p{Pi}|\p{Pf}|&quot;/u,'"')
.gsub("\u2026",'...')
end
def assert_html_equal(expected, actual, msg = nil)
assertion = Proc.new do
expected_doc = Nokogiri::HTML(expected) {|config| config.noblanks}
actual_doc = Nokogiri::HTML(actual) {|config| config.noblanks}
expected_doc.search('//text()').each {|node| node.content = normalize_html node.content}
actual_doc.search('//text()').each {|node| node.content = normalize_html node.content}
ignore_changes = {"+" => Regexp.union(/^\s*id=".*"\s*$/), "-" => nil}
expected_doc.diff(actual_doc) do |change, node|
if change != ' ' && !node.blank? then
break unless node.to_html =~ ignore_changes[change]
end
end
end
assert(assertion.call, msg)
end
class MarkupTest < Minitest::Test
class MarkupFilter < HTML::Pipeline::Filter
def call
filename = context[:filename]
GitHub::Markup.render(filename, File.read(filename)).strip.force_encoding("utf-8")
end
end
Pipeline = HTML::Pipeline.new [
MarkupFilter,
HTML::Pipeline::SanitizationFilter
]
Dir['test/markups/README.*'].each do |readme|
next if readme =~ /html$/
markup = readme.split('/').last.gsub(/^README\./, '')
define_method "test_#{markup}" do
skip "Skipping MediaWiki test because wikicloth is currently not compatible with JRuby." if markup == "mediawiki" && RUBY_PLATFORM == "java"
source = File.read(readme)
expected_file = "#{readme}.html"
expected = File.read(expected_file).rstrip
actual = Pipeline.to_html(nil, :filename => readme)
if source != expected
assert(source != actual, "#{markup} did not render anything")
end
diff = IO.popen("diff -u - #{expected_file}", 'r+') do |f|
f.write actual
f.close_write
f.read
end
if ENV['UPDATE']
File.open(expected_file, 'w') { |f| f.write actual }
end
assert_html_equal expected, actual, <<message
#{File.basename expected_file}'s contents are not html equal to output:
#{diff}
message
end
end
def test_knows_what_it_can_and_cannot_render
assert_equal false, GitHub::Markup.can_render?('README.html', '<h1>Title</h1>')
assert_equal true, GitHub::Markup.can_render?('README.markdown', '=== Title')
assert_equal false, GitHub::Markup.can_render?('README.cmd', 'echo 1')
assert_equal true, GitHub::Markup.can_render?('README.litcoffee', 'Title')
end
def test_each_render_has_a_name
assert_equal "markdown", GitHub::Markup.renderer('README.md', '=== Title').name
assert_equal "redcloth", GitHub::Markup.renderer('README.textile', '* One').name
assert_equal "rdoc", GitHub::Markup.renderer('README.rdoc', '* One').name
assert_equal "org-ruby", GitHub::Markup.renderer('README.org', '* Title').name
assert_equal "creole", GitHub::Markup.renderer('README.creole', '= Title =').name
assert_equal "wikicloth", GitHub::Markup.renderer('README.wiki', '<h1>Title</h1>').name
assert_equal "asciidoctor", GitHub::Markup.renderer('README.adoc', '== Title').name
assert_equal "restructuredtext", GitHub::Markup.renderer('README.rst', 'Title').name
assert_equal "pod", GitHub::Markup.renderer('README.pod', '=head1').name
assert_equal "pod6", GitHub::Markup.renderer('README.pod6', '=begin pod').name
end
def test_rendering_by_symbol
markup = '`test`'
result = /<p><code>test<\/code><\/p>/
assert_match result, GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, markup).strip
assert_match result, GitHub::Markup.render_s(GitHub::Markups::MARKUP_ASCIIDOC, markup).split.join
end
def test_raises_error_if_command_exits_non_zero
GitHub::Markup.command(:doesntmatter, 'test/fixtures/fail.sh', /fail/, ['Java'], 'fail')
assert GitHub::Markup.can_render?('README.java', 'stop swallowing errors')
begin
GitHub::Markup.render('README.java', "stop swallowing errors", symlink: false)
rescue GitHub::Markup::CommandError => e
assert_equal "failure message", e.message.strip
else
fail "an exception was expected but was not raised"
end
end
def test_preserve_markup
content = "Noël"
assert_equal content.encoding.name, GitHub::Markup.render('Foo.rst', content).encoding.name
end
def test_commonmarker_options
assert_equal "<p>hello <!-- raw HTML omitted --> world</p>\n", GitHub::Markup.render("test.md", "hello <bad> world")
assert_equal "<p>hello <bad> world</p>\n", GitHub::Markup.render("test.md", "hello <bad> world", options: {commonmarker_opts: [:UNSAFE]})
assert_equal "<p>hello <!-- raw HTML omitted --> world</p>\n", GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, "hello <bad> world")
assert_equal "<p>hello <bad> world</p>\n", GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, "hello <bad> world", options: {commonmarker_opts: [:UNSAFE]})
assert_equal "<style>.red{color: red;}</style>\n", GitHub::Markup.render("test.md", "<style>.red{color: red;}</style>", options: {commonmarker_opts: [:UNSAFE]})
assert_equal "<style>.red{color: red;}</style>\n", GitHub::Markup.render("test.md", "<style>.red{color: red;}</style>", options: {commonmarker_opts: [:UNSAFE], commonmarker_exts: [:autolink, :table, :strikethrough]})
assert_equal "<style>.red{color: red;}</style>\n", GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, "<style>.red{color: red;}</style>", options: {commonmarker_opts: [:UNSAFE]})
assert_equal "<style>.red{color: red;}</style>\n", GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, "<style>.red{color: red;}</style>", options: {commonmarker_opts: [:UNSAFE], commonmarker_exts: [:autolink, :table, :strikethrough]})
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github-markup.rb | lib/github-markup.rb | module GitHub
module Markup
VERSION = '5.0.1'
Version = VERSION
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup.rb | lib/github/markup.rb | begin
require "linguist"
rescue LoadError
# Rely on extensions instead.
end
require "github/markup/command_implementation"
require "github/markup/gem_implementation"
module GitHub
module Markups
# all of supported markups:
MARKUP_ASCIIDOC = :asciidoc
MARKUP_CREOLE = :creole
MARKUP_MARKDOWN = :markdown
MARKUP_MEDIAWIKI = :mediawiki
MARKUP_ORG = :org
MARKUP_POD = :pod
MARKUP_RDOC = :rdoc
MARKUP_RST = :rst
MARKUP_TEXTILE = :textile
MARKUP_POD6 = :pod6
end
module Markup
extend self
@@markups = {}
def markups
@@markups
end
def markup_impls
markups.values
end
def preload!
markup_impls.each(&:load)
end
def render(filename, content, symlink: false, options: {})
if (impl = renderer(filename, content, symlink: symlink))
impl.render(filename, content, options: options)
else
content
end
end
def render_s(symbol, content, options: {})
raise ArgumentError, 'Can not render a nil.' if content.nil?
if markups.key?(symbol)
markups[symbol].render(nil, content, options: options)
else
content
end
end
def markup(symbol, gem_name, regexp, languages, opts = {}, &block)
impl = GemImplementation.new(regexp, languages, gem_name, &block)
markup_impl(symbol, impl)
end
def markup_impl(symbol, impl)
if markups.key?(symbol)
raise ArgumentError, "The '#{symbol}' symbol is already defined."
end
markups[symbol] = impl
end
def command(symbol, command, regexp, languages, name, &block)
if File.exist?(file = File.dirname(__FILE__) + "/commands/#{command}")
command = file
end
impl = CommandImplementation.new(regexp, languages, command, name, &block)
markup_impl(symbol, impl)
end
def can_render?(filename, content, symlink: false)
renderer(filename, content, symlink: symlink) != nil
end
def renderer(filename, content, symlink: false)
language = language(filename, content, symlink: symlink)
markup_impls.find do |impl|
impl.match?(filename, language)
end
end
def language(filename, content, symlink: false)
return unless defined?(::Linguist)
blob = Linguist::Blob.new(filename, content, symlink: symlink)
Linguist.detect(blob, allow_empty: true)
end
# Define markups
markups_rb = File.dirname(__FILE__) + '/markups.rb'
instance_eval File.read(markups_rb), markups_rb
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markups.rb | lib/github/markups.rb | require "github/markup/markdown"
require "github/markup/rdoc"
require "shellwords"
markup_impl(::GitHub::Markups::MARKUP_MARKDOWN, ::GitHub::Markup::Markdown.new)
markup(::GitHub::Markups::MARKUP_TEXTILE, :redcloth, /textile/, ["Textile"]) do |filename, content, options: {}|
RedCloth.new(content).to_html
end
markup_impl(::GitHub::Markups::MARKUP_RDOC, GitHub::Markup::RDoc.new)
markup(::GitHub::Markups::MARKUP_ORG, 'org-ruby', /org/, ["Org"]) do |filename, content, options: {}|
Orgmode::Parser.new(content, {
:allow_include_files => false,
:skip_syntax_highlight => true
}).to_html
end
markup(::GitHub::Markups::MARKUP_CREOLE, :creole, /creole/, ["Creole"]) do |filename, content, options: {}|
Creole.creolize(content)
end
markup(::GitHub::Markups::MARKUP_MEDIAWIKI, :wikicloth, /mediawiki|wiki/, ["MediaWiki"]) do |filename, content, options: {}|
wikicloth = WikiCloth::WikiCloth.new(:data => content)
WikiCloth::WikiBuffer::HTMLElement::ESCAPED_TAGS << 'tt' unless WikiCloth::WikiBuffer::HTMLElement::ESCAPED_TAGS.include?('tt')
wikicloth.to_html(:noedit => true)
end
markup(::GitHub::Markups::MARKUP_ASCIIDOC, :asciidoctor, /adoc|asc(iidoc)?/, ["AsciiDoc"]) do |filename, content, options: {}|
attributes = {
'showtitle' => '@',
'idprefix' => '',
'idseparator' => '-',
'sectanchors' => nil,
'env' => 'github',
'env-github' => '',
'source-highlighter' => 'html-pipeline'
}
if filename
attributes['docname'] = File.basename(filename, (extname = File.extname(filename)))
attributes['docfilesuffix'] = attributes['outfilesuffix'] = extname
else
attributes['outfilesuffix'] = '.adoc'
end
Asciidoctor::Compliance.unique_id_start_index = 1
Asciidoctor.convert(content, :safe => :secure, :attributes => attributes)
end
command(
::GitHub::Markups::MARKUP_RST,
"python3 #{Shellwords.escape(File.dirname(__FILE__))}/commands/rest2html",
/re?st(\.txt)?/,
["reStructuredText"],
"restructuredtext"
)
command(::GitHub::Markups::MARKUP_POD6, :pod62html, /pod6/, ["Pod 6"], "pod6")
command(::GitHub::Markups::MARKUP_POD, :pod2html, /pod/, ["Pod"], "pod")
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup/rdoc.rb | lib/github/markup/rdoc.rb | require "github/markup/implementation"
require "rdoc"
require "rdoc/markup/to_html"
module GitHub
module Markup
class RDoc < Implementation
def initialize
super(/rdoc/, ["RDoc"])
end
def render(filename, content, options: {})
if ::RDoc::VERSION.to_i >= 4
h = ::RDoc::Markup::ToHtml.new(::RDoc::Options.new)
else
h = ::RDoc::Markup::ToHtml.new
end
h.convert(content)
end
def name
"rdoc"
end
end
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup/gem_implementation.rb | lib/github/markup/gem_implementation.rb | require "github/markup/implementation"
module GitHub
module Markup
class GemImplementation < Implementation
attr_reader :gem_name, :renderer
def initialize(regexp, languages, gem_name, &renderer)
super(regexp, languages)
@gem_name = gem_name.to_s
@renderer = renderer
end
def load
return if defined?(@loaded) && @loaded
require gem_name
@loaded = true
end
def render(filename, content, options: {})
load
renderer.call(filename, content, options: options)
end
def name
gem_name
end
end
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup/implementation.rb | lib/github/markup/implementation.rb | module GitHub
module Markup
class Implementation
attr_reader :regexp
attr_reader :languages
def initialize(regexp, languages)
@regexp = regexp
if defined?(::Linguist)
@languages = languages.map do |l|
lang = Linguist::Language[l]
raise "no match for language #{l.inspect}" if lang.nil?
lang
end
end
end
def load
# no-op by default
end
def render(filename, content, options: {})
raise NotImplementedError, "subclasses of GitHub::Markup::Implementation must define #render"
end
def match?(filename, language)
if defined?(::Linguist)
languages.include? language
else
file_ext_regexp =~ filename
end
end
private
def file_ext_regexp
@file_ext_regexp ||= /\.(#{regexp})\z/
end
end
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
github/markup | https://github.com/github/markup/blob/2b0e7f216904253092c90754cd95aac6d499583d/lib/github/markup/command_implementation.rb | lib/github/markup/command_implementation.rb | require "open3"
require "github/markup/implementation"
module GitHub
module Markup
class CommandError < RuntimeError
end
class CommandImplementation < Implementation
attr_reader :command, :block, :name
def initialize(regexp, languages, command, name, &block)
super(regexp, languages)
@command = command.to_s
@block = block
@name = name
end
def render(filename, content, options: {})
rendered = execute(command, content)
rendered = rendered.to_s.empty? ? content : rendered
call_block(rendered, content)
end
private
def call_block(rendered, content)
if block && block.arity == 2
block.call(rendered, content)
elsif block
block.call(rendered)
else
rendered
end
end
def execute(command, target)
# capture3 blocks until both buffers are written to and the process terminates, but
# it won't allow either buffer to fill up
stdout, stderr, status = Open3.capture3(*command, stdin_data: target)
raise CommandError.new(stderr) unless status.success?
sanitize(stdout, target.encoding)
end
def sanitize(input, encoding)
input.gsub("\r", '').force_encoding(encoding)
end
end
end
end
| ruby | MIT | 2b0e7f216904253092c90754cd95aac6d499583d | 2026-01-04T15:41:08.109033Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.