Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Thermatix/3a65b531607631380913bbef48cf16d6 to your computer and use it in GitHub Desktop.
Save Thermatix/3a65b531607631380913bbef48cf16d6 to your computer and use it in GitHub Desktop.
random libs
require 'yaml'
require 'erb'
require 'pathname'
class Config
Location = 'config.yml'
class << self
def set_defaults(value)
@defaults = value
self
end
def load(loc)
config_loc = loc || Location
if Pathname.new(config_loc).exist?
@store = YAML.load(ERB.new(File.read(config_loc)).result)
else
@store = {}
end
create_config_options
at_exit do
File.open(config_loc,'w') {|f| f.write(@store.to_yaml)}
end
end
def [](key)
@store[key]
end
def []=(key,val)
@store[key] = val
end
def each(&block)
@store.each(&block)
end
private
def create_config_options
@defaults.each { |k,v| @store[k] = v unless @store[k]}
end
def symbolise_keys(hash={})
recurv_hash do |key|
key.to_sym
end
end
def stringify_keys(hash={})
recurv_hash do |key|
key.to_s
end
end
def recurv_hash(hash={})
hash.each_with_object({}) { |(key,value),res| res[yield(key)] = value.is_a? Hash ? symbolise_keys(value) : value }
end
end
end
class Country extend self
# data pulled from: http://www.unc.edu/~rowlett/units/codes/country.htm
ISO_ALPHA2 = [""," AF"," AX"," AL"," "," DZ"," AS"," AD"," AO"," AI"," AQ"," AG"," AR"," AM"," AW"," "," AU"," AT"," AZ",""," BS"," BH"," BD"," BB"," BY"," BE"," BZ"," BJ"," BM"," BT"," BO","BQ"," BA"," BW"," BV"," BR",""," IO"," BN"," BG"," BF"," BI"," KH"," CM"," CA"," CV"," KY"," CF"," TD"," "," CL"," CN",""," CG"," CD"," CK"," CR"," CI"," HR"," CU","CW"," CY"," CZ"," DK"," DJ",""," DM"," DO"," EC"," EG"," SV"," GQ"," ER"," EE"," ET"," "," FO"," FK"," FJ"," FI"," FR",""," GF"," PF"," TF"," GA"," GM"," GE"," DE"," GH"," GI","GB"," GR"," GL"," GD"," GP"," GU"," GT",""," GG"," GN"," GW"," GY"," HT"," HM"," IS"," IN"," ID"," "," IR"," IQ"," IE",""," IM"," IL"," IT"," JM"," JP"," JE"," JO"," KZ"," KE"," KI"," KP"," KR"," KW"," KG"," LA"," LV",""," LB"," LS"," LR"," LY"," LI"," LT"," LU"," MO"," MK"," MG"," MW"," MY"," MV"," ML"," MT",""," MH"," MQ"," MR"," MU"," YT"," MX"," FM"," MD"," MC"," MN","ME"," MS"," NA"," MZ"," NR"," NP"," NL"," AN"," NC"," NZ"," NI"," NE"," NG"," NU"," NF"," MP"," NO"," OM"," PK",""," PW"," PS"," PA"," PG"," PY"," PE"," PH"," PN"," PL"," PT"," PR"," QA"," RE"," RO"," RU",""," RW","BL"," SH"," KN"," LC","MF"," PM"," VC"," WS"," SM"," ST"," SA"," SN"," RS"," SC"," SL"," SG","","SX"," SK"," GS","SS"," "," ES"," LK"," SD"," SR"," SJ"," SZ"," SE"," CH"," SY",""," TW"," TJ"," "," TZ"," TH"," TL"," TG"," TK"," TO"," TT"," TN"," TR"," TM"," TC"," TV"," UG"," UA",""," AE"," GB"," US"," UM"," UY"," UZ"," VU"," VA"," VE"," VN"," VG"," VI"," "," WF"," EH"," YE",""," ZM"," "," ZW"].freeze
ISO_ALPHA3 = [""," AFG"," ALA"," ALB"," "," DZA"," ASM"," AND"," AGO"," AIA"," ATA"," ATG"," ARG"," ARM"," ABW"," "," AUS"," AUT"," AZE",""," BHS"," BHR"," BGD"," BRB"," BLR"," BEL"," BLZ"," BEN"," BMU"," BTN"," BOL","BES"," BIH"," BWA"," BVT"," BRA",""," IOT"," BRN"," BGR"," BFA"," BDI"," KHM"," CMR"," CAN"," CPV"," CYM"," CAF"," TCD"," "," CHL"," CHN",""," COG"," COD"," COK"," CRI"," CIV"," HRV"," CUB","CUW"," CYP"," CZE"," DNK"," DJI",""," DMA"," DOM"," ECU"," EGY"," SLV"," GNQ"," ERI"," EST"," ETH"," "," FRO"," FLK"," FJI"," FIN"," FRA",""," GUF"," PYF"," ATF"," GAB"," GMB"," GEO"," DEU"," GHA"," GIB","GBR"," GRC"," GRL"," GRD"," GLP"," GUM"," GTM",""," GGY"," GIN"," GNB"," GUY"," HTI"," HMD"," ISL"," IND"," IDN"," "," IRN"," IRQ"," IRL",""," IMN"," ISR"," ITA"," JAM"," JPN"," JEY"," JOR"," KAZ"," KEN"," KIR"," PRK"," KOR"," KWT"," KGZ"," LAO"," LVA",""," LBN"," LSO"," LBR"," LBY"," LIE"," LTU"," LUX"," MAC"," MKD"," MDG"," MWI"," MYS"," MDV"," MLI"," MLT",""," MHL"," MTQ"," MRT"," MUS"," MYT"," MEX"," FSM"," MDA"," MCO"," MNG","MNE"," MSR"," NAM"," MOZ"," NRU"," NPL"," NLD"," ANT"," NCL"," NZL"," NIC"," NER"," NGA"," NIU"," NFK"," MNP"," NOR"," OMN"," PAK",""," PLW"," PSE"," PAN"," PNG"," PRY"," PER"," PHL"," PCN"," POL"," PRT"," PRI"," QAT"," REU"," ROU"," RUS",""," RWA","BLM"," SHN"," KNA"," LCA","MAF"," SPM"," VCT"," WSM"," SMR"," STP"," SAU"," SEN"," SRB"," SYC"," SLE"," SGP","","SXM"," SVK"," SGS","SSD"," "," ESP"," LKA"," SDN"," SUR"," SJM"," SWZ"," SWE"," CHE"," SYR",""," TWN"," TJK"," "," TZA"," THA"," TLS"," TGO"," TKL"," TON"," TTO"," TUN"," TUR"," TKM"," TCA"," TUV"," UGA"," UKR",""," ARE"," GBR"," USA"," UMI"," URY"," UZB"," VUT"," VAT"," VEN"," VNM"," VGB"," VIR"," "," WLF"," ESH"," YEM",""," ZMB"," "," ZWE"].freeze
UN_NUMERIC = [""," 004"," 248"," 008"," "," 012"," 016"," 020"," 024"," 660"," 010"," 028"," 032"," 051"," 533"," "," 036"," 040"," 031",""," 044"," 048"," 050"," 052"," 112"," 056"," 084"," 204"," 060"," 064"," 068","535"," 070"," 072"," 074"," 076",""," 086"," 096"," 100"," 854"," 108"," 116"," 120"," 124"," 132"," 136"," 140"," 148"," 830"," 152"," 156",""," 178"," 180"," 184"," 188"," 384"," 191"," 192","531"," 196"," 203"," 208"," 262",""," 212"," 214"," 218"," 818"," 222"," 226"," 232"," 233"," 231"," "," 234"," 238"," 242"," 246"," 250",""," 254"," 258"," 260"," 266"," 270"," 268"," 276"," 288"," 292","826"," 300"," 304"," 308"," 312"," 316"," 320",""," "," 324"," 624"," 328"," 332"," 334"," 352"," 356"," 360"," "," 364"," 368"," 372",""," 833"," 376"," 380"," 388"," 392"," "," 400"," 398"," 404"," 296"," 408"," 410"," 414"," 417"," 418"," 428",""," 422"," 426"," 430"," 434"," 438"," 440"," 442"," 446"," 807"," 450"," 454"," 458"," 462"," 466"," 470",""," 584"," 474"," 478"," 480"," 175"," 484"," 583"," 498"," 492"," 496","499"," 500"," 516"," 508"," 520"," 524"," 528"," 530"," 540"," 554"," 558"," 562"," 566"," 570"," 574"," 580"," 578"," 512"," 586",""," 585"," 275"," 591"," 598"," 600"," 604"," 608"," 612"," 616"," 620"," 630"," 634"," 638"," 642"," 643",""," 646","652"," 654"," 659"," 662","663"," 666"," 670"," 882"," 674"," 678"," 682"," 686"," 688"," 690"," 694"," 702","","534"," 703"," 239"," "," "," 724"," 144"," 736"," 740"," 744"," 748"," 752"," 756"," 760",""," 158"," 762"," "," 834"," 764"," 626"," 768"," 772"," 776"," 780"," 788"," 792"," 795"," 796"," 798"," 800"," 804",""," 784"," 826"," 840"," 581"," 858"," 860"," 548"," 336"," 862"," 704"," 92"," 850"," "," 876"," 732"," 887",""," 894"," "," 716"].freeze
COUNTRY = [""," AFGHANISTAN"," ÅLAND ISLANDS"," ALBANIA","ALDERNEY"," ALGERIA (El Djazaïr)"," AMERICAN SAMOA"," ANDORRA"," ANGOLA"," ANGUILLA"," ANTARCTICA"," ANTIGUA AND BARBUDA"," ARGENTINA"," ARMENIA"," ARUBA"," ASCENSION ISLAND"," AUSTRALIA"," AUSTRIA"," AZERBAIJAN",""," BAHAMAS"," BAHRAIN"," BANGLADESH"," BARBADOS"," BELARUS"," BELGIUM"," BELIZE"," BENIN"," BERMUDA"," BHUTAN"," BOLIVIA","BONAIRE, ST. EUSTATIUS, AND SABA"," BOSNIA AND HERZEGOVINA"," BOTSWANA"," BOUVET ISLAND"," BRAZIL",""," BRITISH INDIAN OCEAN TERRITORY"," BRUNEI DARUSSALAM"," BULGARIA"," BURKINA FASO"," BURUNDI"," CAMBODIA"," CAMEROON"," CANADA"," CAPE VERDE"," CAYMAN ISLANDS"," CENTRAL AFRICAN REPUBLIC"," CHAD (Tchad)"," CHANNEL ISLANDS"," CHILE"," CHINA",""," CONGO, REPUBLIC OF"," CONGO, THE DEMOCRATIC REPUBLIC OF THE (formerly Zaire)"," COOK ISLANDS"," COSTA RICA"," CÔTE D'IVOIRE (Ivory Coast)"," CROATIA (Hrvatska)"," CUBA","CURAÇAO"," CYPRUS"," CZECH REPUBLIC"," DENMARK"," DJIBOUTI",""," DOMINICA"," DOMINICAN REPUBLIC"," ECUADOR"," EGYPT"," EL SALVADOR"," EQUATORIAL GUINEA"," ERITREA"," ESTONIA"," ETHIOPIA","EUROPEAN UNION"," FAEROE ISLANDS"," FALKLAND ISLANDS (MALVINAS)"," FIJI"," FINLAND"," FRANCE",""," FRENCH GUIANA"," FRENCH POLYNESIA"," FRENCH SOUTHERN TERRITORIES"," GABON"," GAMBIA, THE"," GEORGIA"," GERMANY (Deutschland)"," GHANA"," GIBRALTAR","GREAT BRITAIN (United Kingdom)"," GREECE"," GREENLAND"," GRENADA"," GUADELOUPE"," GUAM"," GUATEMALA",""," GUERNSEY"," GUINEA"," GUINEA-BISSAU"," GUYANA"," HAITI"," HEARD ISLAND AND MCDONALD ISLANDS"," ICELAND"," INDIA"," INDONESIA","INTERNATIONAL ORGANIZATIONS "," IRAN (Islamic Republic of Iran)"," IRAQ"," IRELAND",""," ISLE OF MAN"," ISRAEL"," ITALY"," JAMAICA"," JAPAN"," JERSEY"," JORDAN (Hashemite Kingdom of Jordan)"," KAZAKHSTAN"," KENYA"," KIRIBATI"," KOREA (Democratic Peoples Republic of [North] Korea)"," KOREA (Republic of [South] Korea)"," KUWAIT"," KYRGYZSTAN"," LAO PEOPLE'S DEMOCRATIC REPUBLIC"," LATVIA",""," LEBANON"," LESOTHO"," LIBERIA"," LIBYA (Libyan Arab Jamahirya)"," LIECHTENSTEIN (Fürstentum Liechtenstein)"," LITHUANIA"," LUXEMBOURG"," MACAO (Special Administrative Region of China)"," MACEDONIA (Former Yugoslav Republic of Macedonia)"," MADAGASCAR"," MALAWI"," MALAYSIA"," MALDIVES"," MALI"," MALTA",""," MARSHALL ISLANDS"," MARTINIQUE"," MAURITANIA"," MAURITIUS"," MAYOTTE"," MEXICO"," MICRONESIA (Federated States of Micronesia)"," MOLDOVA"," MONACO"," MONGOLIA","MONTENEGRO"," MONTSERRAT"," NAMIBIA"," MOZAMBIQUE (Moçambique)"," NAURU"," NEPAL"," NETHERLANDS"," NETHERLANDS ANTILLES (obsolete)"," NEW CALEDONIA"," NEW ZEALAND"," NICARAGUA"," NIGER"," NIGERIA"," NIUE"," NORFOLK ISLAND"," NORTHERN MARIANA ISLANDS"," NORWAY"," OMAN"," PAKISTAN",""," PALAU"," PALESTINIAN TERRITORIES"," PANAMA"," PAPUA NEW GUINEA"," PARAGUAY"," PERU"," PHILIPPINES"," PITCAIRN"," POLAND"," PORTUGAL"," PUERTO RICO"," QATAR"," RÉUNION"," ROMANIA"," RUSSIAN FEDERATION",""," RWANDA","SAINT BARTHÉLEMY "," SAINT HELENA"," SAINT KITTS AND NEVIS"," SAINT LUCIA","SAINT MARTIN (French portion) "," SAINT PIERRE AND MIQUELON"," SAINT VINCENT AND THE GRENADINES"," SAMOA (formerly Western Samoa)"," SAN MARINO (Republic of)"," SAO TOME AND PRINCIPE"," SAUDI ARABIA (Kingdom of Saudi Arabia)"," SENEGAL"," SERBIA (Republic of Serbia)"," SEYCHELLES"," SIERRA LEONE"," SINGAPORE","","SINT MAARTEN"," SLOVAKIA (Slovak Republic)"," SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS","SOUTH SUDAN","SOVIET UNION (Internet code still used)"," SPAIN (España)"," SRI LANKA (formerly Ceylon)"," SUDAN"," SURINAME"," SVALBARD AND JAN MAYEN"," SWAZILAND"," SWEDEN"," SWITZERLAND (Confederation of Helvetia)"," SYRIAN ARAB REPUBLIC",""," TAIWAN (\"Chinese Taipei\" for IOC)"," TAJIKISTAN","TANGANYIKA"," TANZANIA"," THAILAND"," TIMOR-LESTE (formerly East Timor)"," TOGO"," TOKELAU"," TONGA"," TRINIDAD AND TOBAGO"," TUNISIA"," TURKEY"," TURKMENISTAN"," TURKS AND CAICOS ISLANDS"," TUVALU"," UGANDA"," UKRAINE",""," UNITED ARAB EMIRATES"," UNITED KINGDOM"," UNITED STATES"," UNITED STATES MINOR OUTLYING ISLANDS"," URUGUAY"," UZBEKISTAN"," VANUATU"," VATICAN CITY (Holy See)"," VENEZUELA"," VIET NAM"," VIRGIN ISLANDS, BRITISH"," VIRGIN ISLANDS, U.S.","YUGOSLAVIA (Internet code still used)"," WALLIS AND FUTUNA"," WESTERN SAHARA (formerly Spanish Sahara)"," YEMEN (Yemen Arab Republic)",""," ZAMBIA (formerly Northern Rhodesia)","ZANZIBAR"," ZIMBABWE"].freeze
VALID_TYPES = [:iso_alpha2, :iso_alpha3, :un_numerical, :country ].freeze
attr :from_type, :to_type, :input
#dynamic form
# example: find_country = Country.match("AFG").to_ISO_ALPHA3.for_Country
# or find_country = Country.match["AFG"].to(:iso_alpha3).for_target(:country)
# or find_country = Contry.match("AFG").to_ISO_ALPHA3.for_target(:country)
# or find_alpha_3 = Country.match["United Kingdom"].to_country.for_target(:iso_alpha3)
def match.[](input)
@search = input
self
end
def match search
@search = input
self
end
def semethod_missing(meth, *args, &block)
if meth.to_s =~ /^to_(.+)$/
to($1)
elsif meth.to_s =~ /^for_(.+)$/
for_target($1)
elsif meth.to_s =~ /^get_(.+)$/
get($1)
else
super
end
end
def to to
@compare_to = convert(to)
self
end
def for_target target
@target = convert(target)
return @target[@compare_to.index(@search)]
end
def get input
return convert input
end
#verbose static form (as in can't dynamicly change what your looking for, where your looking for and the target)
#example: = find_country = Country.match_country_to_alpha3_for("AFG")
def match_country_for_alpha2_for code
COUNTRY[ISO_ALPHA2.index(code.upcase)]
end
def match_country_for_alpha3_for code
COUNTRY[ISO_ALPHA3.index(code.upcase)]
end
def match_country_for_numeric_for code
COUNTRY[UN_NUMERIC.index(code.upcase)]
end
def match_alpha2_for_country_for country
ISO_ALPHA2[COUNTRY.index(country.upcase)]
end
def match_alpha3_for_country_for country
ISO_ALPHA3[COUNTRY.index(country.upcase)]
end
def match_numeric_for_country_for country
UN_NUMERIC[COUNTRY.index(country.upcase)]
end
private
def convert input
Country.const_get(input.to_s.uppercase)
end
end
require "curb"
require 'cgi'
module Curb_DSL
Regex = {
cookie_header: /Set-Cookie: /
}
def self.included(base)
base.extend Singleton
base.instance_eval do
attr_reader :curl, :headers,:payload, :username, :password, :auth_type, :uri, :ssl, :redirects, :type_converter,:cookies, :form_field_name, :form_fields
[:get, :post, :put, :delete, :head, :options, :patch, :link, :unlink].each do |func_name|
define_method func_name do |&block|
make_request_of func_name.to_s.upcase, &block
end
end
[:password,:username,:payload, :auth_type, :uri, :ssl, :redirects,:type_converter,:cookies,:form_field_name,:error_handler, :proxy_url, :proxy_port, :proxy_tunnel, :proxy_pass, :follow_location, :base, :routes].each do |func_name|
define_method "set_#{func_name}" do |value|
self.instance_variable_set :"@#{func_name}", value
end
end
end
def form_field name,value
@form_fields ||= []
if @form_field_name
@form_fields.push(Curl::PostField.content([("%[%]" % [@form_field_name,name]),value.to_s]))
else
@form_fields.push(Curl::PostField.content(name ,value.to_s))
end
end
end
module Singleton
def request(&block)
self.new(&block).body
end
def query_params(value)
Curl::postalize(value)
end
end
def initialize(&block)
@headers ||= {}
instance_eval(&block) if block_given?
end
def header(name, content)
@headers ||= {}
@headers[name] = content
end
def del_header(key)
@headers.delete(key)
end
def make_request_of(request_method,i_e =nil,&block)
i_e ||= @ignore_error
@resp_cookies = nil
@curl = Curl::Easy.new(@uri) do |http|
setup_request request_method, http
end
@curl.ssl_verify_peer = @ssl ||false
# @curl.ignore_content_length = true
if @form_fields
@curl.http_post(*@form_field)
else
@curl.http request_method
end
if @curl.response_code == 301
@uri = @curl.redirect_url
make_request_of request_method, i_e
end
if @curl.response_code != 200
if @error_handler
puts @error_handler.call unless i_e
end
end
@ignore_error = false
end
def create_url(key,*args)
@base % (@routes[key] % args)
end
def add_route(key,url)
@routes[key] = url
end
def status_code
@curl.response_code
end
def decode_html(string)
CGI.unescapeHTML(string)
end
def encode_html(string)
CGI.escapeHTML(string)
end
def post_body
get_payload
end
def ignore_error
@ignore_error = true
end
def body
@curl.body
end
def response_code
@curl.response_code
end
def response_headers
return @resp_headers if @resp_headers
_, *@resp_headers = curl.header_str.split(/[\r\n]+/).map(&:strip)
@resp_headers = Hash[@resp_headers.flat_map{ |s| s.scan(/^(\S+): (.+)/) }]
end
def response_cookies
@resp_cookies ||=
@curl.header_str.split("\r\n").each_with_object({}) do |header,headers|
if header =~ Regex[:cookie_header]
header.gsub(Regex[:cookie_header],'').split(';').each do |segment|
unless segment =~ /secure/
headers[$1.strip.downcase] = $2.gsub('"','') if segment =~ /(.*?)=(.*?)($|;|,(?! ))/
end
end
end
end
end
def query_params(value)
Curl::postalize(value)
end
private
def setup_request(method,http)
http.headers['request-method'] = method.to_s
http.headers.update(headers || {})
http.max_redirects = @redirects || 3
http.post_body = get_payload || nil
http.http_auth_types = @auth_type || nil
http.username = @username || nil
http.password = @password || nil
http.useragent = "curb"
http.multipart_form_post = @form_field_name ? true : false
http.proxy_tunnel = @proxy_tunnel || nil
http.proxy_url = @proxy_url || nil
http.proxy_port = @proxy_url || nil
http.proxypwd = @proxy_pass|| nil
if @cookies
http.enable_cookies = true
http.cookies = (@cookies.is_a? String) ? @cookies : @cookies.inject("") {|cookies,data| "%s%s=%s;" % data.unshift(cookies) }
end
http
end
def get_payload
if @type_converter
@type_converter.call(@payload)
else
@payload
end
end
end
quire 'jwt'
class Sessions
Encryption_Key_Type = ['prime256v1', 'ES256'].freeze
class << self
def encryt_hash full_hash
deal_with_hash full_hash, :encrypt
end
def decode_hash full_hash
deal_with_hash full_hash, :decode
end
def encrypt item_hash,type
deal_with item_hash, :encrypt, type
end
def decode item_hash,type
deal_with item_hash, :decode, type
end
private
def deal_with_hash full_hash, action
case action
when :decode
send(:"#{action}_this",full_hash,instance_variable_get("@hash_#{action}_key")).first.inject({}) do |hash,(type,item_hash)|
hash[type] = deal_with(item_hash,action,type).first
hash
end
when :encrypt
send(:"#{action}_this",full_hash.inject({}) do |hash,(type,item_hash)|
hash[type] = deal_with item_hash,action,type
hash
end,instance_variable_get("@hash_#{action}_key"))
end
end
def deal_with item_hash, action, type
raise "This function only takes encrypt, decode actions, you provided(#{action})" unless [:encrypt,:decode].include?(action)
send(:"#{action}_this", item_hash, instance_variable_get("@#{type}_#{action}_key"))
end
def generate_private_key
::OpenSSL::PKey::EC.new(Encryption_Key_Type.first).generate_key
end
def generate_public_key_with private_key
::OpenSSL::PKey::EC.new private_key
end
def encrypt_this value, key
JWT.encode(value, key, Encryption_Key_Type.last)
end
def decode_this value, key
JWT.decode(value, key)
end
end
@user_encrypt_key = generate_private_key
@user_decode_key = generate_public_key_with(@user_encrypt_key)
@important_encrypt_key = generate_private_key
@important_decode_key = generate_public_key_with(@important_encrypt_key)
@details_encrypt_key = generate_private_key
@details_decode_key = generate_public_key_with(@details_encrypt_key)
@hash_encrypt_key = generate_private_key
@hash_decode_key = generate_public_key_with(@hash_encrypt_key)
end
class Headers
def initialize(app=nil)
@app = app
end
def call(env,key='HEADERS')
env[key] = self.class.get_headers(env)
@app.call(env)
end
def self.get_headers(env,start="HTTP")
env.select {|k,v| k.start_with? "#{start}_"}.
inject({}) {|h,(k,v)| h[k.sub(/^#{start}_/,'').downcase.to_sym] = v;h }
end
def self.call(env,key='HEADERS')
['200',{ 'Content-Type'=> 'application/json' },[(env.fetch(key){get_headers(env)}).to_json]]
end
end

about

These are just a bunch of random single file library's I wrote to use in various projects, some might eventually be turned into full gem based libraries.

random libs

  • node.rb - a library for creating node based trees
  • config_loader.rb - a library for loading a config from a file and ensuring it's written back to the file before the app exits
  • state_machine.rb - a library for creating state machines
  • country.rb - a libary for converting between country codes
  • curb_dsl.rb - a library for turning curb into a dsl
  • snake_case.rb - a lirbrary for monkeypatching a method to the String class that converts camel_case to SnakeCase
  • hash_encrypt.rb - a library for encrypting and decrypting hash's for use in things like JWT

rack middlewares

  • headers.rb - a library for adding headers to the env varible under 'HEADERS'
    • x_headers.rb - a library for adding X-headers to the env variavle under 'X-HEADERS', inherites from headers.rb
  • subdomain_dispatcher.rb - a library for matching sub-domains to other rack based apps
class Node
include Enumerable
attr_accessor :childs,:init, :data, :ident
def initialize(init={},ident=:root)
@ident = ident
@childs = {}
@init = init.dup
@data = init.dup
end
def each(&block)
block.call(self)
@childs.map do |key,child|
child.each(&block)
end
end
def <=>(other_node)
@data <=> other_node.data
end
def [](*keys)
return self if @childs.empty?
[*keys.flatten].inject(self) do |node,ident|
node.find {|n| n.ident == ident}
end
end
def new_child(ident,&block)
child = self.class.new(@init,ident)
child.tap(&block) if block_given?
@childs[ident] = child
end
def pretty_print(pp)
self.each {|node| pp.text(node.ident || "" );puts "\n";pp.pp_hash node.data}
end
end
class String
def snake_case
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
module State_Machine
def check_intial_state
raise "no initial state set, please use `set_initial_state STATE`" unless get_current_state
end
def get_current_state
send(self.class.state_name)
end
def set_current_state value
send("#{self.class.state_name}=",value)
end
def use_(callback)
if callback
if callback.lambda?
callback.call
else
send(callback)
end
end
end
def can_transition_(from)
[from].flatten.include?(get_current_state)
end
def using_state_action
action = self.class.state_actions[get_current_state]
if action.respond_to?(:call)
self.instance_eval(&action)
else
send(action)
end
end
module API
def state_action state, func_name=nil, &action
@state_actions ||= {}
if state.kind_of?(Array)
state.each { |name| @state_actions[name] = func_name || action }
else
@state_actions[state] = func_name || action
end
end
def state_actions
@state_actions
end
def state_name
@state_name || 'current_state'
end
def set_state_name name
@state_name = name
end
def create_state state
@states ||= []
@states << state
define_method "#{state}?" do
check_intial_state
get_current_state == state
end
end
def create_states states
states.each do |state|
create_state state
end
end
def set_initial_state state
@initial_state = state
define_state(state_name){state}
end
def event name,data, &callback
@events ||= []
@events << name
define_method "#{name}!" do |*args|
check_intial_state
use_(data[:before])
if can_transition_(data[:from])
set_current_state data[:to]
callback.call(*args) if block_given?
else
use_(data[:fail])
end
end
define_method "may_#{name}?" do
check_intial_state
get_current_state == data[:from]
end
end
end
def self.included(base)
base.extend API
end
end
# subdomain dispatching middleware
class Subdomain_Dispatcher
def initialize(app,&block)
@app = app
@domains = {}
@ssl = false
@subs = []
@errors = {
ssl: ['403', {'Content-Type' => 'text/html'}, ['Forbidden, This resource is HTTPS only']]
}
instance_exec(&block)
end
def ssl_only
@ssl = true
yield
@ssl = false
end
def set domain,app
@subs << (d = domain.to_s)
@domains[d] = {
app: app,
ssl: @ssl
}
end
def call(env)
sub = subdomain(env)
if @subs.include?(sub)
if @domains[sub][:ssl]
if env['rack.url_scheme'] == 'https'
@domains[sub][:app].call(env)
else
@errors[:ssl]
end
else
@domains[sub][:app].call(env)
end
else
@app.call(env)
end
end
private
def subdomain(env)
env['HTTP_HOST'].split('.').first
end
end
class X_Headers < Headers
def call(env)
super(env,'X-HEADERS')
end
def self.get_headers(env)
super(env,'X-HTTP')
end
def self.call(env)
super(env,'X-HEADERS')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment