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 |
|---|---|---|---|---|---|---|---|---|
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/property_test.rb | test/unit/property_test.rb | require 'test_helper'
class PropertyTest < Test::Unit::TestCase
context "A Property instance" do
setup do
data = load_fixture('music_artist')
@type = Ken::Type.new(data)
@value_property = @type.properties[1]
@object_property = @type.properties[3]
end
should 'be a valid property instance' do
@value_property.should be_kind_of(Ken::Property)
@object_property.should be_kind_of(Ken::Property)
end
should 'have a type' do
@value_property.type.should be_kind_of(Ken::Type)
@object_property.type.should be_kind_of(Ken::Type)
end
should 'distinguish wheter it is an object or value type' do
@value_property.object_type?.should == false
@object_property.object_type?.should == true
end
end # context
end # PropertyTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/view_test.rb | test/unit/view_test.rb | require 'test_helper'
class ViewTest < Test::Unit::TestCase
context "A View instance" do
setup do
Ken::Logger.new(STDOUT, :info)
data = load_fixture('the_police')
@the_police = Ken::Resource.new(data)
@view = @the_police.views.first
end
should "have a type" do
@view.type.should_not be_nil
@view.type.should be_kind_of(Ken::Type)
end
should "have properties" do
@view.properties.should_not be_nil
@view.properties.each { |p| p.should be_kind_of(Ken::Property)}
end
should "have attributes" do
@view.attributes.should_not be_nil
@view.attributes.each { |p| p.should be_kind_of(Ken::Attribute)}
end
context "when accessing a direct attribute" do
setup do
@genre = @view.attribute('genre')
@album = @view.album
end
should "be kind of Ken::Attribute" do
@genre.should be_kind_of(Ken::Attribute)
@album.should be_kind_of(Ken::Attribute)
end
should "be able to get values" do
@genre.should have(6).values
@album.should have(14).values
end
should "raise AttributeNotFound when invalid propertyname is supplied" do
@view.not_existing_attribute.should be_nil
end
end # context
end # context
end # ViewTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/examples/artist_links.rb | examples/artist_links.rb | require 'pathname'
require 'rubygems'
# displays all links related to music/artists
# low level api through Ken.session.mqlread is used here
EXAMPLES_ROOT = Pathname(__FILE__).dirname.expand_path
require EXAMPLES_ROOT.parent + 'lib/ken'
Ken::Session.new('http://www.freebase.com', 'ma', '*****')
puts "collecting artist links... this might take a while..."
artist_links = []
# execute query
artists = Ken.session.mqlread([{
:type => "/music/artist",
:id => nil,
:"/common/topic/webpage" => [{:uri => nil}],
:home_page => [{:uri => nil}]
}], :cursor => true)
# collect artist links
artists.each do |artist|
artist["/common/topic/webpage"].each do |webpage|
artist_links << webpage["uri"] unless artist_links.include?(webpage["uri"])
end
artist["home_page"].each do |homepage|
artist_links << homepage["uri"] unless artist_links.include?(homepage["uri"])
end
end
# print artist links
artist_links.each do |link|
puts link
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/examples/artist.rb | examples/artist.rb | require 'pathname'
require 'rubygems'
EXAMPLES_ROOT = Pathname(__FILE__).dirname.expand_path
require EXAMPLES_ROOT.parent + 'lib/ken'
Ken::Logger.new(STDOUT, :info)
Ken::Session.new('http://www.freebase.com', 'ma', 'xxxxx')
resource = Ken.get('/en/the_police')
resource.views.each do |view|
puts view
puts "="*20
view.attributes.each do |a|
puts a.property
puts "-"*20
puts a
puts # newline
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken.rb | lib/ken.rb | require 'pathname'
require 'rubygems'
require 'net/http'
require 'json'
require 'extlib/assertions'
require 'addressable/uri'
dir = Pathname(__FILE__).dirname.expand_path + 'ken'
require dir + 'util'
require dir + 'session'
require dir + 'resource'
require dir + 'type'
require dir + 'view'
require dir + 'property'
require dir + 'attribute'
require dir + 'collection'
require dir + 'topic'
require dir + 'logger'
# init logger as soon as the library is required
Ken::Logger.new(STDOUT, :error)
# init default session
Ken::Session.new('http://api.freebase.com', 'ma', 'xxxxx')
module Ken
extend Extlib::Assertions
# store query as a constant here.
# if the hash gets updated using
# #merge! or #update, this will mean
# that it actually stores the last
# query used. there are 2 sides to this.
# on the one hand, it isn't really a
# constant anymore (ruby doesn't complain)?
# on the other hand, there is no need to
# create a new object everytime a query is
# executed. maybe this is fine, maybe not,
# this needs to be discussed.
FETCH_DATA_QUERY = {
# :id => id, # needs to be merge!d in instance method
:guid => nil,
:name => nil,
:"ken:type" => [{
:id => nil,
:name => nil,
:properties => [{
:id => nil,
:name => nil,
:expected_type => nil,
:unique => nil,
:reverse_property => nil,
:master_property => nil,
}]
}],
:"/type/reflect/any_master" => [
{
:id => nil,
:link => nil,
:name => nil,
:optional => true,
:limit => 999999
}
],
:"/type/reflect/any_reverse" => [
{
:id => nil,
:link => nil,
:name => nil,
:optional => true,
:limit => 999999
}
],
:"/type/reflect/any_value" => [
{
:link => nil,
:value => nil,
:optional => true,
:limit => 999999
# TODO: support multiple language
# :lang => "/lang/en",
# :type => "/type/text"
}
]
}
# Executes an Mql Query against the Freebase API and returns the result as
# a <tt>Collection</tt> of <tt>Resources</tt>.
#
# performs a cursored query unless there's a limit specified
# == Examples
#
# Ken.all(:name => "Apple", :type => "/music/album")
#
# Ken.all(
# :directed_by => "George Lucas",
# :starring => [{
# :actor => "Harrison Ford"
# }],
# :type => "/film/film"
# )
# @api public
def self.all(options = {})
assert_kind_of 'options', options, Hash
query = { :name => nil }.merge!(options).merge!(:id => nil)
result = Ken.session.mqlread([ query ], :cursor => !options[:limit])
Ken::Collection.new(result.map { |r| Ken::Resource.new(r) })
end
# Executes an Mql Query against the Freebase API and returns the result wrapped
# in a <tt>Resource</tt> Object.
#
# == Examples
#
# Ken.get('/en/the_police') => #<Resource id="/en/the_police" name="The Police">
# @api public
def self.get(id)
Ken::Resource.get(id)
end
end # module Ken
| ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/resource.rb | lib/ken/resource.rb | module Ken
class Resource
include Extlib::Assertions
extend Extlib::Assertions
attr_reader :data
# initializes a resource using a json result
def initialize(data)
assert_kind_of 'data', data, Hash
@schema_loaded, @attributes_loaded, @data = false, false, data
@data_fechted = data["/type/reflect/any_master"] != nil
end
# Executes an Mql Query against the Freebase API and returns the result wrapped
# in a <tt>Resource</tt> Object.
#
# == Examples
#
# Ken::Resource.get('/en/the_police') => #<Resource id="/en/the_police" name="The Police">
# @api public
def self.get(id)
assert_kind_of 'id', id, String
result = Ken.session.mqlread(FETCH_DATA_QUERY.merge!(:id => id))
raise ResourceNotFound unless result
Ken::Resource.new(result)
end
# resource id
# @api public
def id
@data["id"] || ""
end
# resource guid
# @api public
def guid
@data['guid'] || ""
end
# resource name
# @api public
def name
@data["name"] || ""
end
# @api public
def to_s
name || id || ""
end
# @api public
def inspect
result = "#<Resource id=\"#{id}\" name=\"#{name || "nil"}\">"
end
# returns all assigned types
# @api public
def types
load_schema! unless schema_loaded?
@types
end
# returns all available views based on the assigned types
# @api public
def views
@views ||= Ken::Collection.new(types.map { |type| Ken::View.new(self, type) })
end
# returns individual view based on the requested type id
# @api public
def view(type)
views.each { |v| return v if v.type.id =~ /^#{Regexp.escape(type)}$/}
nil
end
# returns individual type based on the requested type id
# @api public
def type(type)
types.each { |t| return t if t.id =~ /^#{Regexp.escape(type)}$/}
nil
end
# returns all the properties from all assigned types
# @api public
def properties
@properties = Ken::Collection.new
types.each do |type|
@properties.concat(type.properties)
end
@properties
end
# returns all attributes for every type the resource is an instance of
# @api public
def attributes
load_attributes! unless attributes_loaded?
@attributes.values
end
# search for an attribute by name and return it
# @api public
def attribute(name)
attributes.each { |a| return a if a.property.id == name }
nil
end
# returns true if type information is already loaded
# @api public
def schema_loaded?
@schema_loaded
end
# returns true if attributes are already loaded
# @api public
def attributes_loaded?
@attributes_loaded
end
# returns true if json data is already loaded
# @api public
def data_fetched?
@data_fetched
end
private
# executes the fetch data query in order to load the full set of types, properties and attributes
# more info at http://lists.freebase.com/pipermail/developers/2007-December/001022.html
# @api private
def fetch_data
return @data if @data["/type/reflect/any_master"]
@data = Ken.session.mqlread(FETCH_DATA_QUERY.merge!(:id => id))
end
# loads the full set of attributes using reflection
# information is extracted from master, value and reverse attributes
# @api private
def load_attributes!
fetch_data unless data_fetched?
# master & value attributes
raw_attributes = Ken::Util.convert_hash(@data["/type/reflect/any_master"])
raw_attributes.merge!(Ken::Util.convert_hash(@data["/type/reflect/any_value"]))
@attributes = {}
raw_attributes.each_pair do |a, d|
properties.select { |p| p.id == a}.each do |p|
@attributes[p.id] = Ken::Attribute.create(d, p)
end
end
# reverse properties
raw_attributes = Ken::Util.convert_hash(@data["/type/reflect/any_reverse"])
raw_attributes.each_pair do |a, d|
properties.select { |p| p.master_property == a}.each do |p|
@attributes[p.id] = Ken::Attribute.create(d, p)
end
end
@attributes_loaded = true
end
# loads the resource's metainfo
# @api private
def load_schema!
fetch_data unless data_fetched?
@types = Ken::Collection.new(@data["ken:type"].map { |type| Ken::Type.new(type) })
@schema_loaded = true
end
end # class Resource
end # module Ken | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/collection.rb | lib/ken/collection.rb | module Ken
class Collection < Array
# add a linebreak after each entry
def to_s
self.inject("") { |m,i| "#{m}#{i.to_s}\n"}
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/session.rb | lib/ken/session.rb | module Ken
class << self
attr_accessor :session
end
# A class for returing errors from the freebase api.
# For more infomation see the freebase documentation:
class ReadError < ArgumentError
attr_accessor :code, :msg
def initialize(code,msg)
self.code = code
self.msg = msg
end
def message
"#{code}: #{msg}"
end
end
class AttributeNotFound < StandardError ; end
class PropertyNotFound < StandardError ; end
class ResourceNotFound < StandardError ; end
class TopicNotFound < StandardError ; end
class ViewNotFound < StandardError ; end
# partially taken from chris eppstein's freebase api
# http://github.com/chriseppstein/freebase/tree
class Session
public
# Initialize a new Ken Session
# Ken::Session.new(host{String, IO}, username{String}, password{String})
#
# @param host<String> the API host
# @param username<String> freebase username
# @param password<String> user password
def initialize(host, username, password)
@host = host
@username = username
@password = password
Ken.session = self
# TODO: check connection
Ken.logger.info("connection established.")
end
SERVICES = {
:mqlread => '/api/service/mqlread',
:mqlwrite => '/api/service/mqlwrite',
:blurb => '/api/trans/blurb',
:raw => '/api/trans/raw',
:login => '/api/account/login',
:upload => '/api/service/upload',
:topic => '/experimental/topic',
:search => '/api/service/search'
}
# get the service url for the specified service.
def service_url(svc)
"#{@host}#{SERVICES[svc]}"
end
SERVICES.each_key do |k|
define_method("#{k}_service_url") do
service_url(k)
end
end
# raise an error if the inner response envelope is encoded as an error
def handle_read_error(inner)
unless inner['code'][0, '/api/status/ok'.length] == '/api/status/ok'
Ken.logger.error "Read Error #{inner.inspect}"
error = inner['messages'][0]
raise ReadError.new(error['code'], error['message'])
end
end # handle_read_error
# Perform a mqlread and return the results
# Specify :cursor => true to batch the results of a query, sending multiple requests if necessary.
# TODO: should support multiple queries
# you should be able to pass an array of queries
def mqlread(query, options = {})
Ken.logger.info ">>> Sending Query: #{query.to_json}"
cursor = options[:cursor]
if cursor
query_result = []
while cursor
response = get_query_response(query, cursor)
query_result += response['result']
cursor = response['cursor']
end
else
response = get_query_response(query, cursor)
cursor = response['cursor']
query_result = response['result']
end
query_result
end
def raw_content(id, options = {})
response = http_request raw_service_url+id, options
Ken.logger.info "<<< Received Raw Content Response: #{response}"
response
end
def blurb_content(id, options = {})
response = http_request blurb_service_url+id, options
Ken.logger.info "<<< Received Blurb Content Response: #{response}"
response
end
def topic(id, options = {})
options.merge!({:id => id})
response = http_request topic_service_url+"/standard", options
result = JSON.parse response
inner = result[id]
handle_read_error(inner)
Ken.logger.info "<<< Received Topic Response: #{inner['result'].inspect}"
inner['result']
end
def search(query, options = {})
Ken.logger.info ">>> Sending Search Query: #{query}"
options.merge!({:query => query})
response = http_request search_service_url, options
result = JSON.parse response
handle_read_error(result)
Ken.logger.info "<<< Received Topic Response: #{result['result'].inspect}"
result['result']
end
protected
# returns parsed json response from freebase mqlread service
def get_query_response(query, cursor=nil)
envelope = { :qname => {:query => query, :escape => false }}
envelope[:qname][:cursor] = cursor if cursor
response = http_request mqlread_service_url, :queries => envelope.to_json
result = JSON.parse response
inner = result['qname']
handle_read_error(inner)
Ken.logger.info "<<< Received Response: #{inner['result'].inspect}"
inner
end
# encode parameters
def params_to_string(parameters)
parameters.keys.map {|k| "#{URI.encode(k.to_s)}=#{URI.encode(parameters[k].to_s)}" }.join('&')
end
# does the dirty work
def http_request(url, parameters = {})
params = params_to_string(parameters)
url << '?'+params unless params !~ /\S/
Ken.logger.info "<<< URL queried: #{url}"
return Net::HTTP.get_response(::URI.parse(url)).body
fname = "#{MD5.md5(params)}.mql"
open(fname,"w") do |f|
f << response
end
Ken.logger.info("Wrote response to #{fname}")
end
end # class Session
end # module Ken | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/logger.rb | lib/ken/logger.rb | require "time"
# ==== Public Ken Logger API
#
# Logger taken from Merb/Datamapper :)
#
# To replace an existing logger with a new one:
# Ken.logger.set_log(log{String, IO},level{Symbol, String})
#
# Available logging levels are:
# :off, :fatal, :error, :warn, :info, :debug
#
# Logging via:
# Ken.logger.fatal(message<String>)
# Ken.logger.error(message<String>)
# Ken.logger.warn(message<String>)
# Ken.logger.info(message<String>)
# Ken.logger.debug(message<String>)
#
# Flush the buffer to
# Ken.logger.flush
#
# Remove the current log object
# Ken.logger.close
#
# ==== Private Ken Logger API
#
# To initialize the logger you create a new object, proxies to set_log.
# ken::Logger.new(log{String, IO}, level{Symbol, String})
#
# Logger will not create the file until something is actually logged
# This avoids file creation on Ken init when it creates the
# default logger.
module Ken
class << self #:nodoc:
attr_accessor :logger
end
class Logger
attr_accessor :aio
attr_accessor :delimiter
attr_reader :level
attr_reader :buffer
attr_reader :log
# @note
# Ruby (standard) logger levels:
# off: absolutely nothing
# fatal: an unhandleable error that results in a program crash
# error: a handleable error condition
# warn: a warning
# info: generic (useful) information about system operation
# debug: low-level information for developers
#
# Ken::Logger::LEVELS[:off, :fatal, :error, :warn, :info, :debug]
LEVELS =
{
:off => 99999,
:fatal => 7,
:error => 6,
:warn => 4,
:info => 3,
:debug => 0
}
def level=(new_level)
@level = LEVELS[new_level.to_sym]
reset_methods(:close)
end
private
# The idea here is that instead of performing an 'if' conditional check on
# each logging we do it once when the log object is setup
def set_write_method
@log.instance_eval do
# Determine if asynchronous IO can be used
def aio?
@aio = !RUBY_PLATFORM.match(/java|mswin/) &&
!(@log == STDOUT) &&
@log.respond_to?(:write_nonblock)
end
# Define the write method based on if aio an be used
undef write_method if defined? write_method
if aio?
alias :write_method :write_nonblock
else
alias :write_method :write
end
end
end
def initialize_log(log)
close if @log # be sure that we don't leave open files laying around.
@log = log || "log/dm.log"
end
def reset_methods(o_or_c)
if o_or_c == :open
alias internal_push push_opened
elsif o_or_c == :close
alias internal_push push_closed
end
end
def push_opened(string)
message = Time.now.httpdate
message << delimiter
message << string
message << "\n" unless message[-1] == ?\n
@buffer << message
flush # Force a flush for now until we figure out where we want to use the buffering.
end
def push_closed(string)
unless @log.respond_to?(:write)
log = Pathname(@log)
log.dirname.mkpath
@log = log.open('a')
@log.sync = true
end
set_write_method
reset_methods(:open)
push(string)
end
alias internal_push push_closed
def prep_msg(message, level)
level << delimiter << message
end
public
# To initialize the logger you create a new object, proxies to set_log.
# Ken::Logger.new(log{String, IO},level{Symbol, String})
#
# @param log<IO,String> either an IO object or a name of a logfile.
# @param log_level<String> the message string to be logged
# @param delimiter<String> delimiter to use between message sections
# @param log_creation<Boolean> log that the file is being created
def initialize(*args)
set_log(*args)
end
# To replace an existing logger with a new one:
# Ken.logger.set_log(log{String, IO},level{Symbol, String})
#
# @param log<IO,String> either an IO object or a name of a logfile.
# @param log_level<Symbol> a symbol representing the log level from
# {:off, :fatal, :error, :warn, :info, :debug}
# @param delimiter<String> delimiter to use between message sections
# @param log_creation<Boolean> log that the file is being created
def set_log(log, log_level = :off, delimiter = " ~ ", log_creation = false)
delimiter ||= " ~ "
if log_level && LEVELS[log_level.to_sym]
self.level = log_level.to_sym
else
self.level = :debug
end
@buffer = []
@delimiter = delimiter
initialize_log(log)
Ken.logger = self
self.info("Logfile created") if log_creation
end
# Flush the entire buffer to the log object.
# Ken.logger.flush
#
def flush
return unless @buffer.size > 0
@log.write_method(@buffer.slice!(0..-1).join)
end
# Close and remove the current log object.
# Ken.logger.close
#
def close
flush
@log.close if @log.respond_to?(:close)
@log = nil
end
# Appends a string and log level to logger's buffer.
# @note
# Note that the string is discarded if the string's log level less than the
# logger's log level.
# @note
# Note that if the logger is aio capable then the logger will use
# non-blocking asynchronous writes.
#
# @param level<Fixnum> the logging level as an integer
# @param string<String> the message string to be logged
def push(string)
internal_push(string)
end
alias << push
# Generate the following logging methods for Ken.logger as described
# in the API:
# :fatal, :error, :warn, :info, :debug
# :off only gets a off? method
LEVELS.each_pair do |name, number|
unless name.to_s == 'off'
class_eval <<-EOS, __FILE__, __LINE__
# DOC
def #{name}(message)
self.<<( prep_msg(message, "#{name}") ) if #{name}?
end
EOS
end
class_eval <<-EOS, __FILE__, __LINE__
# DOC
def #{name}?
#{number} >= level
end
EOS
end
end # class Logger
end # module Ken | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/type.rb | lib/ken/type.rb | module Ken
class Type
include Extlib::Assertions
# initializes a resource using a json result
def initialize(data)
assert_kind_of 'data', data, Hash
@data = data
end
# access property info
# @api public
def properties
@properties ||= Ken::Collection.new(@data["properties"].map { |property| Ken::Property.new(property, self) })
end
# type id
# @api public
def id
@data["id"]
end
# type name
# @api public
def name
@data["name"]
end
# @api public
def to_s
name || id || ""
end
# @api public
def inspect
result = "#<Type id=\"#{id}\" name=\"#{name || "nil"}\">"
end
# delegate to property_get
def method_missing sym
property_get(sym.to_s)
end
private
# @api private
# search for a property by name and return it
def property_get(name)
properties.each { |p| return p if p.id =~ /\/#{name}$/ }
raise PropertyNotFound
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/topic.rb | lib/ken/topic.rb | module Ken
class Topic
include Extlib::Assertions
extend Extlib::Assertions
attr_reader :data
# initializes a topic using a json result
def initialize(data)
assert_kind_of 'data', data, Hash
@data = data
@schema_loaded, @attributes_loaded = false, false
end
# Retrieves a topic using the Topic API by Freebase
# returns a <tt>Topic</tt> Object.
#
# == Examples
#
# Ken::Topic.get('/en/the_police') => #<Topic id="/en/the_police" name="The Police">
# @api public
def self.get(id)
assert_kind_of 'id', id, String
result = Ken.session.topic(id)
raise TopicNotFound unless result
Ken::Topic.new(result)
end
# topic id
# @api public
def id
@data["id"] || ""
end
# topic aliases
def aliases
@data["alias"]
end
# topic freebase url
def url
@data["url"]
end
# topic name
# @api public
def name
text
end
# topic description
# @api public
def description
@data["description"]
end
# topic text
# @api public
def text
@data["text"]
end
# topic thumbnail
def thumbnail
@data["thumbnail"]
end
# @api public
def to_s
name || id || ""
end
# @api public
def inspect
result = "#<Topic id=\"#{id}\" name=\"#{name || "nil"}\">"
end
# topic webpages
# currently returned as an array of hashes containing the keys "text" and "url"
# that hashes may be wrapped into a Webpage class later
# @api public
def webpages
@data["webpage"]
end
# returns all assigned types
# @api public
def types
load_schema! unless schema_loaded?
@types
end
# returns individual type based on the requested type id
# @api public
def type(type)
types.each { |t| return t if t.id =~ /^#{Regexp.escape(type)}$/}
nil
end
# returns all the properties from all assigned types
# @api public
def properties
@properties = Ken::Collection.new
types.each do |type|
@properties.concat(type.properties)
end
@properties
end
# returns all attributes for every type the topic is an instance of
# @api public
def attributes
load_attributes! unless attributes_loaded?
@attributes.values
end
# returns all available views based on the assigned types
# @api public
def views
@views ||= Ken::Collection.new(types.map { |type| Ken::View.new(self, type) })
end
# returns individual view based on the requested type id
# @api public
def view(type)
views.each { |v| return v if v.type.id =~ /^#{Regexp.escape(type)}$/}
nil
end
# search for an attribute by name and return it
# @api public
def attribute(name)
attributes.each { |a| return a if a.property.id == name }
nil
end
# returns true if type information is already loaded
# @api public
def schema_loaded?
@schema_loaded
end
# returns true if attributes are already loaded
# @api public
def attributes_loaded?
@attributes_loaded
end
private
# loads the full set of attributes using reflection
# information is extracted from master, value and reverse attributes
# @api private
def load_attributes!
load_schema! unless schema_loaded?
@attributes = {}
@data["properties"].each do |id, data|
# skip mediator properties for now
if !data["properties"]
values = []
data["values"].each do |value|
values << { "id" => value["id"], "name" => value["text"], "value" => value["text"] }
end
@attributes[id] = Ken::Attribute.create(values, properties.select { |p| p.id == id }.first)
end
end
@attributes_loaded = true
end
# loads the topic's metainfo
# @api private
def load_schema!
result = {}
@data["type"].each do |type|
result[type["id"]] = { "id" => type["id"], "name" => type["text"], "properties" => [] }
end
@data["properties"].each do |id, data|
result[id.gsub(/\/\w*$/, "")]["properties"] << {
"expected_type" => data["expected_type"]["id"],
"id" => id,
"name" => data["text"],
"unique" => true
}
end
@types = Ken::Collection.new(result.values.map { |type| Ken::Type.new(type) })
@schema_loaded = true
end
end # class Topic
end # module Ken | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/attribute.rb | lib/ken/attribute.rb | module Ken
class Attribute
include Extlib::Assertions
attr_reader :property
# initializes a resource by json result
def initialize(data, property)
assert_kind_of 'data', data, Array
assert_kind_of 'property', property, Ken::Property
@data, @property = data, property
end
# factory method for creating an attribute instance
# @api semipublic
def self.create(data, property)
Ken::Attribute.new(data, property)
end
# @api public
def to_s
subject.to_s
end
# @api public
def inspect
result = "#<Attribute property=\"#{property.id || "nil"}\">"
end
# returns a collection of values
# in case of a unique property the array holds just one value
# @api public
def values
subject
end
# unique properties can have at least one value
# @api public
def unique?
@property.unique?
end
# object type properties always link to resources
# @api public
def object_type?
@property.object_type?
end
# returns true if the property is a value type
# value type properties refer to simple values like /type/text
# @api public
def value_type?
@property.value_type?
end
# type, which attribute values of that property are expected to have
# @api public
def expected_type
@property.expected_type
end
private
# initializes the subject if used for the first time
def subject
@subject ||= Ken::Collection.new(@data.map { |r| object_type? ? Ken::Resource.new(r) : r["value"] })
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/view.rb | lib/ken/view.rb | # provides an interface to view a subject (resource or topic) as a specific type
# provides an interface for working with attributes, properties
module Ken
class View
include Extlib::Assertions
# initializes a subject (resource or topic) by json result
def initialize(subject, type)
assert_kind_of 'type', type, Ken::Type
@subject, @type = subject, type
end
# @api public
def to_s
@type.to_s
end
# return correspondent type
# @api public
def type
@type
end
# @api public
def inspect
result = "#<View type=\"#{type.id || "nil"}\">"
end
# returns attributes which are member of the view's type
# @api public
def attributes
@subject.attributes.select { |a| a.property.type == @type}
end
# search for an attribute by name and return it
# @api public
def attribute(name)
attributes.each { |a| return a if a.property.id =~ /\/#{name}$/ }
nil
end
# returns properties which are member of the view's type
# @api public
def properties
@subject.properties.select { |p| p.type == @type}
end
# delegate to attribute
def method_missing sym
attribute(sym.to_s)
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/property.rb | lib/ken/property.rb | module Ken
class Property
include Extlib::Assertions
VALUE_TYPES = %w{
/type/id
/type/int
/type/float
/type/boolean
/type/text
/type/rawstring
/type/uri
/type/datetime
/type/key
}
# initializes a resource by json result
def initialize(data, type)
assert_kind_of 'data', data, Hash
assert_kind_of 'type', type, Ken::Type
@data, @type = data, type
end
# property id
# @api public
def id
@data["id"]
end
# property name
# @api public
def name
@data["name"]
end
# @api public
def to_s
name || id || ""
end
# @api public
def inspect
result = "#<Property id=\"#{id}\" expected_type=\"#{expected_type || "nil"}\" unique=\"#{unique?}\" object_type=\"#{object_type?}\">"
end
# returns the type of which the property is a part of
# every property always has exactly one type.
# that's why /type/property/schema is a unique property
# @api public
def type
@type
end
# reverse property, which represent incoming links
# @api public
def reverse_property
@data["reverse_property"]
end
# master property, which represent an outgoing link (or primitive value)
# @api public
def master_property
@data["master_property"]
end
# returns true if the property is unique
# @api public
def unique?
return @data["unique"]==true
end
# returns true if the property is an object type
# @api public
def object_type?
!value_type?
end
# returns true if the property is a value type
# @api public
def value_type?
VALUE_TYPES.include?(expected_type)
end
# type, which attribute values of that property are expected to have
# @api public
def expected_type
@data["expected_type"]
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/lib/ken/util.rb | lib/ken/util.rb | module Ken
module Util
# magic hash conversion
def convert_hash(source)
source.inject({}) do |result, item|
if result[item["link"]]
result[item["link"]] << { "id" => item["id"], "name" => item["name"], "value" => item["value"] }
else
result[item["link"]] = []
result[item["link"]] << { "id" => item["id"], "name" => item["name"], "value" => item["value"] }
end
result
end
end
module_function :convert_hash
end
end
| ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/test/google_drive_test.rb | test/google_drive_test.rb | require 'minitest/autorun'
require 'fileutils'
require 'google_drive'
# Test the client lib!
class TestGoogleDrive < MiniTest::Test
def setup
@drive = ::GoogleDrive.new
@old_sheet_file_id = '0AiOYF21HkoowdEZ4Ukkyc09nb2czQUxUYldidTB4Q1E'
@new_sheet_file_id = '1vIICbbfHJ8lYSthiDWTNypZulrMResi9zPRjv4ePJJU'
@doc_file_id = '1lH-Nr_8UBOkvk8OdcdFoDez3OFIJxkawGVkwlMB-BjQ'
end
def test_find
file = @drive.find @old_sheet_file_id
assert_equal file['title'], 'Example Middleman Google Drive worksheet'
file = @drive.find @new_sheet_file_id
assert_equal file['title'], 'Example Middleman Google Drive worksheet'
end
def test_export
content = @drive.export @doc_file_id, :txt
assert_nil content =~ /^<html>/
content = @drive.export @doc_file_id, :html
assert_not_nil content =~ /^<html>/
end
def test_export_to_file
filename = @drive.export_to_file(@doc_file_id, :html)
assert_equal '.html', File.extname(filename)
assert File.exist?(filename), "Export file is missing #{filename}"
assert_not_nil File.read(filename) =~ /^<html>/
File.unlink(filename)
[@new_sheet_file_id, @old_sheet_file_id].each do |file_id|
filename = @drive.export_to_file(file_id, :xlsx)
assert_equal '.xlsx', File.extname(filename)
assert File.exist?(filename), "Export file is missing #{filename}"
File.unlink(filename)
end
end
def test_prepare_spreadsheet
[@old_sheet_file_id, @new_sheet_file_id].each do |file_id|
#filename = "/tmp/google_drive_#{file_id}.xlsx"
filename = @drive.export_to_file(file_id, :xlsx)
assert_equal '.xlsx', File.extname(filename)
assert File.exist?(filename), "Export file is missing #{filename}"
data = @drive.prepare_spreadsheet(filename)
assert_has_key data, 'microcopy'
assert_has_key data['microcopy'], 'help'
File.unlink(filename)
end
end
def test_copy_file
end
def assert_has_key(hash, key, msg=nil)
assert hash.key?(key), msg || "The key '#{key}' is missing from #{hash}"
end
def assert_not_nil(thing, msg=nil)
assert !thing.nil?, msg
end
end
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/lib/middleman_extension.rb | lib/middleman_extension.rb | require 'middleman-google_drive'
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/lib/middleman-google_drive.rb | lib/middleman-google_drive.rb | require 'middleman-core'
Middleman::Extensions.register :google_drive do
require 'middleman-google_drive/extension'
Middleman::GoogleDrive::Extension
end
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/lib/google_drive.rb | lib/google_drive.rb | require 'middleman-google_drive/version'
require 'mime/types'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
require 'rubyXL'
# Convience wrapper for Google Drive
#
# You can override the location of the client secrets and oauth2 JSON files with
# the environment variables `GOOGLE_CLIENT_SECRETS` and `GOOGLE_DRIVE_OAUTH`.
#
# If you plan to run Middleman on a server, you can use Google's server to server
# authentication. This will kick in if you define the environment variables
# `GOOGLE_OAUTH_PERSON`, `GOOGLE_OAUTH_ISSUER` and either `GOOGLE_OAUTH_KEYFILE`
# or `GOOGLE_OAUTH_PRIVATE_KEY`.
class GoogleDrive
# Google API Client object
attr_reader :client
# Constructor. Loads all params from envionment variables.
def initialize
@credentials = ENV['GOOGLE_DRIVE_OAUTH'] || File.expand_path(
'~/.google_drive_oauth2.json')
@client_secrets = ENV['GOOGLE_CLIENT_SECRETS'] || File.expand_path(
'~/.google_client_secrets.json')
@person = ENV['GOOGLE_OAUTH_PERSON']
@issuer = ENV['GOOGLE_OAUTH_ISSUER']
@key_path = ENV['GOOGLE_OAUTH_KEYFILE']
@private_key = ENV['GOOGLE_OAUTH_PRIVATE_KEY']
# try to read the file,
# throw errors if not readable or not found
if @key_path
@key = Google::APIClient::KeyUtils.load_from_pkcs12(
@key_path, 'notasecret')
elsif @private_key
@key = OpenSSL::PKey::RSA.new(
@private_key, 'notasecret')
end
@_files = {}
@_spreadsheets = {}
do_auth
end
## Friendly Google Drive access
# Find a Google Drive file
# Takes the key of a Google Drive file and returns a hash of meta data. The returned hash is
# formatted as a
# {Google Drive resource}[https://developers.google.com/drive/v2/reference/files#resource].
#
# @param file_id [String] file id
# @return [Hash] file meta data
def find(file_id)
return @_files[file_id] unless @_files[file_id].nil?
drive = @client.discovered_api('drive', 'v2')
# get the file metadata
resp = @client.execute(
api_method: drive.files.get,
parameters: { fileId: file_id })
# die if there's an error
fail GoogleDriveError, resp.error_message if resp.error?
@_files[file_id] = resp.data
end
# Export a file
# Returns the file contents
#
# @param file_id [String] file id
# @param type [:excel, :text, :html] export type
# @return [String] file contents
def export(file_id, type)
list_resp = find(file_id)
# decide which mimetype we want
mime = mime_for(type).content_type
# Grab the export url.
if list_resp['exportLinks'] && list_resp['exportLinks'][mime]
uri = list_resp['exportLinks'][mime]
else
raise "Google doesn't support exporting file id #{file_id} to #{type}"
end
# get the export
get_resp = @client.execute(uri: uri)
# die if there's an error
fail GoogleDriveError, get_resp.error_message if get_resp.error?
# contents
get_resp.body
end
# Export a file and save to disk
# Returns the local path to the file
#
# @param file_id [String] file id
# @param type [:excel, :text, :html] export type
# @param filename [String] where to save the spreadsheet
# @return [String] path to the excel file
def export_to_file(file_id, type, filename = nil)
contents = export(file_id, type)
if filename.nil?
# get a temporary file. The export is binary, so open the tempfile in
# write binary mode
fp = Tempfile.create(
['googledoc', ".#{type}"], binmode: mime_for(type.to_s).binary?)
filename = fp.path
fp.write(contents)
fp.close
else
open(filename, 'wb') { |f| f.write(contents) }
end
filename
end
# Make a copy of a Google Drive file
#
# @param file_id [String] file id
# @param title [String] title for the newly created file
# @return [Hash] hash containing the id/key and url of the new file
def copy(file_id, title = nil, visibility = :private)
drive = @client.discovered_api('drive', 'v2')
if title.nil?
copied_file = drive.files.copy.request_schema.new
else
copied_file = drive.files.copy.request_schema.new('title' => title)
end
cp_resp = @client.execute(
api_method: drive.files.copy,
body_object: copied_file,
parameters: { fileId: file_id, visibility: visibility.to_s.upcase })
if cp_resp.error?
fail CreateError, cp_resp.error_message
else
return { id: cp_resp.data['id'], url: cp_resp.data['alternateLink'] }
end
end
alias_method :copy_doc, :copy
# Get the mime type from a file extension
#
# @param extension [String] file ext
# @return [String, nil] mime type for the file
def mime_for(extension)
MIME::Types.of(extension.to_s).first
end
## Spreadsheet utilities
# Parse a spreadsheet
# Reduces the spreadsheet to a no-frills hash, suitable for serializing and passing around.
#
# @param filename [String] path to xls file
# @return [Hash] spreadsheet contents
def prepare_spreadsheet(filename)
# open the file with RubyXL
xls = RubyXL::Parser.parse(filename)
data = {}
xls.worksheets.each do |sheet|
title = sheet.sheet_name
# if the sheet is called microcopy, copy or ends with copy, we assume
# the first column contains keys and the second contains values.
# Like tarbell.
if %w(microcopy copy).include?(title.downcase) ||
title.downcase =~ /[ -_]copy$/
data[title] = load_microcopy(sheet.extract_data)
else
# otherwise parse the sheet into a hash
data[title] = load_table(sheet.extract_data)
end
end
return data
end
# Take a two-dimensional array from a spreadsheet and create a hash. The first
# column is used as the key, and the second column is the value. If the key
# occurs more than once, the value becomes an array to hold all the values
# associated with the key.
#
# @param table [Array<Array>] 2d array of cell values
# @return [Hash] spreadsheet contents
def load_microcopy(table)
data = {}
table.each_with_index do |row, i|
next if i == 0 # skip the header row
next if row.nil? || row.length < 2 || row[0].nil? # skip empty, incomplete or blank rows
# Did we already create this key?
if data.keys.include? row[0]
# if the key name is reused, create an array with all the entries
if data[row[0]].is_a? Array
data[row[0]] << row[1]
else
data[row[0]] = [data[row[0]], row[1]]
end
else
# add this row's key and value to the hash
data[row[0]] = row[1]
end
end
data
end
# Take a two-dimensional array from a spreadsheet and create an array of hashes.
#
# @param table [Array<Array>] 2d array of cell values
# @return [Array<Hash>] spreadsheet contents
def load_table(table)
return [] if table.length < 2
header = table.shift # Get the header row
# remove blank rows
table.reject! do |row|
row.nil? || row
.map { |r| r.nil? || r.to_s.strip.empty? }
.reduce(true) { |m, col| m && col }
end
table.map do |row|
# zip headers with current row, convert it to a hash
header.zip(row).to_h unless row.nil?
end
end
## Authentication
# Returns true if we're using a private key to autheticate (like on a server).
# @return [Boolean]
def server?
!local?
end
# Returns true if we're using local oauth2 (like on your computer).
# @return [Boolean]
def local?
@key.nil?
end
# Delete cached credentials
def clear_auth
File.delete @credentials if @key.nil?
end
# Authenticate with Google and create the @client object
def do_auth
if local?
@client = Google::APIClient.new(
application_name: 'Middleman',
application_version: Middleman::GoogleDrive::VERSION
)
begin
file_storage = Google::APIClient::FileStorage.new(@credentials)
rescue URI::InvalidURIError
File.delete @credentials
file_storage = Google::APIClient::FileStorage.new(@credentials)
end
if file_storage.authorization.nil?
unless File.exist? @client_secrets
fail ConfigurationError, 'You need to create a client_secrets.json file and save it to ~/.google_client_secrets.json.'
end
puts <<-MSG
Please login via your web browser. We opened the tab for you...
MSG
client_secrets = Google::APIClient::ClientSecrets.load(@client_secrets)
flow = Google::APIClient::InstalledAppFlow.new(
client_id: client_secrets.client_id,
client_secret: client_secrets.client_secret,
scope: ['https://www.googleapis.com/auth/drive']
)
@client.authorization = flow.authorize(file_storage)
else
@client.authorization = file_storage.authorization
end
else
@client = Google::APIClient.new(
application_name: 'Middleman',
application_version: Middleman::GoogleDrive::VERSION,
authorization: Signet::OAuth2::Client.new(
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
audience: 'https://accounts.google.com/o/oauth2/token',
person: @person,
issuer: @issuer,
signing_key: @key,
scope: ['https://www.googleapis.com/auth/drive']
)
)
@client.authorization.fetch_access_token!
end
nil
end
class GoogleDriveError < StandardError; end
class DoesNotExist < GoogleDriveError; end
class CreateError < GoogleDriveError; end
class ConfigurationError < GoogleDriveError; end
end
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/lib/middleman-google_drive/version.rb | lib/middleman-google_drive/version.rb | module Middleman
module GoogleDrive
VERSION = '0.3.13'
end
end
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
voxmedia/middleman-google_drive | https://github.com/voxmedia/middleman-google_drive/blob/363d0fd581eee5922f3894f53a6b5e940e673730/lib/middleman-google_drive/extension.rb | lib/middleman-google_drive/extension.rb | require 'middleman-core'
require 'google_drive'
require 'archieml'
module Middleman
module GoogleDrive
# Middle man extension that loads the google doc data
class Extension < Middleman::Extension
option :load_sheets, {}, 'Key for a google spreadsheet or a hash of google spreadsheets to load. Hash value is the id or slug of the spreadsheet to load, hash key is the data attribute to load the sheet data into.'
option :load_docs, {}, 'Key for a google doc or a hash of google docs to load as text. Hash value is the Google key of the spreadsheet to load, hash key is the data attribute to load the content into.'
option :load_docs_html, {}, 'Key for a google doc or a hash of google docs to load as HTML. Hash value is the Google key of the spreadsheet to load, hash key is the data attribute to load the content into.'
option :load_docs_archieml, {}, 'Key for a google doc or a hash of google docs to load and parse as ArchieML. Hash value is the Google key of the spreadsheet to load, hash key is the data attribute to load the content into.'
def initialize(klass, options_hash = {}, &block)
super
begin
@drive = ::GoogleDrive.new
@app = klass.inst
@cache_dir = File.join(@app.root, 'google_drive_cache')
Dir.mkdir(@cache_dir) unless Dir.exist?(@cache_dir)
handle_option(options.load_sheets, :xlsx)
handle_option(options.load_docs, :txt)
handle_option(options.load_docs_html, :html)
handle_option(options.load_docs_archieml, :archieml)
rescue Faraday::ConnectionFailed => ex
puts "== Can't connect to Google (#{ex.message})"
end
end
def handle_option(option, type)
if option.is_a? Hash
option.each do |name, key|
store_data(name, load_doc(key.to_s, type))
end
elsif type == :xlsx
load_doc(option.to_s, type).each do |name, sheet|
store_data(name, sheet)
end
else
store_data('doc', load_doc(option.to_s, type))
end
end
def load_doc(key, type)
filename = data_path("#{key}.#{type}")
doc = @drive.find(key)
puts <<-MSG
== Loading data from Google Doc "#{doc['title']}"
== #{doc['alternateLink']}
MSG
case type.to_sym
when :xlsx
if @drive.server?
filename = @drive.export_to_file(key, :xlsx)
else
@drive.export_to_file(key, :xlsx, filename)
end
ret = @drive.prepare_spreadsheet(filename)
File.unlink(filename) if @drive.server?
when :archieml
if @drive.server?
ret = Archieml.load(@drive.export(key, :txt))
else
@drive.export_to_file(key, :txt, filename)
ret = Archieml.load(File.read(filename))
end
else
if @drive.server?
ret = @drive.export(key, type)
else
@drive.export_to_file(key, type, filename)
ret = File.read(filename)
end
end
return ret
rescue ::Faraday::ConnectionFailed => exc
puts "== FAILED to load Google Doc \"#{exc.message}\""
return load_local_copy(filename)
rescue ::GoogleDrive::GoogleDriveError => exc
puts "== FAILED to load Google Doc \"#{exc.message}\""
unless @drive.server?
puts <<-MSG
Could not load the Google Doc.
Things to check:
- Make sure the Google Doc key is correct
- Make sure you're logging in with the correct account
- Make sure you have access to the document
MSG
@drive.clear_auth
end
return load_local_copy(filename)
end
def load_local_copy(filename)
if File.exist? filename
puts '== Loading Google Doc from local cache'
type = File.extname(filename).gsub('.','').to_sym
case type
when :xlsx
return @drive.prepare_spreadsheet(filename)
when :archieml
return Archieml.load(File.read(filename))
else
return File.read(filename)
end
else
puts '== No local copy of Google Doc'
return nil
end
end
def data_path(basename)
File.join(@cache_dir, basename)
end
def store_data(key, data)
@app.data.store(key, data)
end
end
end
end
| ruby | BSD-3-Clause | 363d0fd581eee5922f3894f53a6b5e940e673730 | 2026-01-04T17:45:38.751473Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "dotenv"
require "faraday"
require "faraday/retry"
require "open_router"
require "pry"
require "raix"
Dotenv.load
retry_options = {
max: 2,
interval: 0.05,
interval_randomness: 0.5,
backoff_factor: 2
}
OpenRouter.configure do |config|
config.faraday do |f|
f.request :retry, retry_options
f.response :logger, ::Logger.new($stdout), { headers: true, bodies: true, errors: true } do |logger|
logger.filter(/(Bearer) (\S+)/, '\1[REDACTED]')
end
end
end
Raix.configure do |config|
config.openrouter_client = OpenRouter::Client.new(access_token: ENV["OR_ACCESS_TOKEN"])
config.openai_client = OpenAI::Client.new(access_token: ENV["OAI_ACCESS_TOKEN"]) do |f|
f.request :retry, retry_options
f.response :logger, ::Logger.new($stdout), { headers: true, bodies: true, errors: true } do |logger|
logger.filter(/(Bearer) (\S+)/, '\1[REDACTED]')
end
end
end
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/spec/raix/rails_spec.rb | spec/raix/rails_spec.rb | # frozen_string_literal: true
RSpec.describe Raix::Rails do
it "has a version number" do
expect(Raix::Rails::VERSION).not_to be nil
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/spec/raix/function_dispatch_spec.rb | spec/raix/function_dispatch_spec.rb | # frozen_string_literal: true
class WhatIsTheWeather
include Raix::ChatCompletion
include Raix::FunctionDispatch
function :check_weather, "Check the weather for a location", location: { type: "string" } do |arguments|
"The weather in #{arguments[:location]} is hot and sunny"
end
def initialize
self.seed = 9999
transcript << { user: "What is the weather in Zipolite, Oaxaca?" }
end
end
RSpec.describe WhatIsTheWeather do
subject { described_class.new }
it "can call a function and loop to provide text response" do
response = subject.chat_completion(openai: "gpt-4o", loop: true)
expect(response).to include("hot and sunny")
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/spec/raix/chat_completion_spec.rb | spec/raix/chat_completion_spec.rb | # frozen_string_literal: true
class MeaningOfLife
include Raix::ChatCompletion
def initialize
self.model = "meta-llama/llama-3-8b-instruct:free"
self.seed = 9999 # try to get reproduceable results
transcript << { user: "What is the meaning of life?" }
end
end
RSpec.describe MeaningOfLife do
subject { described_class.new }
it "does a completion with OpenAI" do
expect(subject.chat_completion(openai: "gpt-4o")).to include("meaning of life is")
end
it "does a completion with OpenRouter" do
expect(subject.chat_completion).to include("meaning of life is")
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/lib/raix.rb | lib/raix.rb | # frozen_string_literal: true
require_relative "raix/rails/version"
require_relative "raix/chat_completion"
require_relative "raix/function_dispatch"
require_relative "raix/prompt_declarations"
# The Raix module provides configuration options for the Raix gem.
module Raix
# The Configuration class holds the configuration options for the Raix gem.
class Configuration
# The temperature option determines the randomness of the generated text.
# Higher values result in more random output.
attr_accessor :temperature
# The max_tokens option determines the maximum number of tokens to generate.
attr_accessor :max_tokens
# The model option determines the model to use for text generation. This option
# is normally set in each class that includes the ChatCompletion module.
attr_accessor :model
# The openrouter_client option determines the default client to use for communicatio.
attr_accessor :openrouter_client
# The openai_client option determines the OpenAI client to use for communication.
attr_accessor :openai_client
DEFAULT_MAX_TOKENS = 1000
DEFAULT_MODEL = "meta-llama/llama-3-8b-instruct:free"
DEFAULT_TEMPERATURE = 0.0
# Initializes a new instance of the Configuration class with default values.
def initialize
self.temperature = DEFAULT_TEMPERATURE
self.max_tokens = DEFAULT_MAX_TOKENS
self.model = DEFAULT_MODEL
end
end
class << self
attr_writer :configuration
end
# Returns the current configuration instance.
def self.configuration
@configuration ||= Configuration.new
end
# Configures the Raix gem using a block.
def self.configure
yield(configuration)
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/lib/raix/prompt_declarations.rb | lib/raix/prompt_declarations.rb | # frozen_string_literal: true
require "ostruct"
module Raix
# The PromptDeclarations module provides a way to chain prompts and handle
# user responses in a serialized manner (in the order they were defined),
# with support for functions if the FunctionDispatch module is also included.
module PromptDeclarations
extend ActiveSupport::Concern
extend ChatCompletion
module ClassMethods # rubocop:disable Style/Documentation
# Adds a prompt to the list of prompts.
#
# @param system [Proc] A lambda that generates the system message.
# @param text [Proc] A lambda that generates the prompt text. (Required)
# @param success [Proc] The block of code to execute when the prompt is answered.
# @param parameters [Hash] Additional parameters for the completion API call
def prompt(text:, system: nil, success: nil, params: {})
name = Digest::SHA256.hexdigest(text.inspect)[0..7]
prompts << begin
OpenStruct.new({ name:, system:, text:, success:, params: })
end
define_method(name) do |response|
if Rails.env.local?
puts "_" * 80
puts "PromptDeclarations#response:"
puts "#{text.source_location} (#{name})"
puts response
puts "_" * 80
end
return response if success.nil?
return send(success, response) if success.is_a?(Symbol)
instance_exec(response, &success)
end
end
# the list of prompts declared at class level
def prompts
@prompts ||= []
end
# getter/setter for system prompt declared at class level
def system_prompt(prompt = nil)
prompt ? @system_prompt = prompt.squish : @system_prompt
end
end
# Executes the chat completion process based on the class-level declared prompts.
# The response to each prompt is added to the transcript automatically and returned.
#
# Prompts require at least a `text` lambda parameter.
#
# @param params [Hash] Parameters for the chat completion override those defined in the current prompt.
# @option params [Boolean] :raw (false) Whether to return the raw response or dig the text content.
#
# Uses system prompt in following order of priority:
# - system lambda specified in the prompt declaration
# - system_prompt instance method if defined
# - system_prompt class-level declaration if defined
#
# TODO: shortcut syntax passes just a string prompt if no other options are needed.
#
# @raise [RuntimeError] If no prompts are defined.
#
def chat_completion(params: {}, raw: false)
raise "No prompts defined" unless self.class.prompts.present?
current_prompts = self.class.prompts.clone
while (@current_prompt = current_prompts.shift)
__system_prompt = instance_exec(&@current_prompt.system) if @current_prompt.system.present? # rubocop:disable Lint/UnderscorePrefixedVariableName
__system_prompt ||= system_prompt if respond_to?(:system_prompt)
__system_prompt ||= self.class.system_prompt.presence
transcript << { system: __system_prompt } if __system_prompt
transcript << { user: instance_exec(&@current_prompt.text) } # text is required
params = @current_prompt.params.merge(params)
super(params:, raw:).then do |response|
transcript << { assistant: response }
@last_response = send(@current_prompt.name, response)
end
end
@last_response
end
# Returns the model parameter of the current prompt or the default model.
#
# @return [Object] The model parameter of the current prompt or the default model.
def model
@current_prompt.params[:model] || super
end
# Returns the temperature parameter of the current prompt or the default temperature.
#
# @return [Float] The temperature parameter of the current prompt or the default temperature.
def temperature
@current_prompt.params[:temperature] || super
end
# Returns the max_tokens parameter of the current prompt or the default max_tokens.
#
# @return [Integer] The max_tokens parameter of the current prompt or the default max_tokens.
def max_tokens
@current_prompt.params[:max_tokens] || super
end
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/lib/raix/chat_completion.rb | lib/raix/chat_completion.rb | # frozen_string_literal: true
require "active_support/concern"
require "active_support/core_ext/object/blank"
require "open_router"
require "openai"
module Raix
# The `ChatCompletion`` module is a Rails concern that provides a way to interact
# with the OpenRouter Chat Completion API via its client. The module includes a few
# methods that allow you to build a transcript of messages and then send them to
# the API for completion. The API will return a response that you can use however
# you see fit. If the response includes a function call, the module will dispatch
# the function call and return the result. Which implies that function calls need
# to be defined on the class that includes this module. (Note: You should probably
# use the `FunctionDispatch` module to define functions instead of doing it manually.)
module ChatCompletion
extend ActiveSupport::Concern
attr_accessor :frequency_penalty, :logit_bias, :logprobs, :loop, :min_p, :model, :presence_penalty,
:repetition_penalty, :response_format, :stream, :temperature, :max_tokens, :seed, :stop, :top_a,
:top_k, :top_logprobs, :top_p, :tools, :tool_choice, :provider
# This method performs chat completion based on the provided transcript and parameters.
#
# @param params [Hash] The parameters for chat completion.
# @option loop [Boolean] :loop (false) Whether to loop the chat completion after function calls.
# @option params [Boolean] :json (false) Whether to return the parse the response as a JSON object.
# @option params [Boolean] :openai (false) Whether to use OpenAI's API instead of OpenRouter's.
# @option params [Boolean] :raw (false) Whether to return the raw response or dig the text content.
# @return [String|Hash] The completed chat response.
def chat_completion(params: {}, loop: false, json: false, raw: false, openai: false)
messages = transcript.flatten.compact.map { |msg| transform_message_format(msg) }
raise "Can't complete an empty transcript" if messages.blank?
# used by FunctionDispatch
self.loop = loop
# set params to default values if not provided
params[:frequency_penalty] ||= frequency_penalty.presence
params[:logit_bias] ||= logit_bias.presence
params[:logprobs] ||= logprobs.presence
params[:max_tokens] ||= max_tokens.presence || Raix.configuration.max_tokens
params[:min_p] ||= min_p.presence
params[:presence_penalty] ||= presence_penalty.presence
params[:provider] ||= provider.presence
params[:repetition_penalty] ||= repetition_penalty.presence
params[:response_format] ||= response_format.presence
params[:seed] ||= seed.presence
params[:stop] ||= stop.presence
params[:temperature] ||= temperature.presence || Raix.configuration.temperature
params[:tool_choice] ||= tool_choice.presence
params[:tools] ||= tools.presence
params[:top_a] ||= top_a.presence
params[:top_k] ||= top_k.presence
params[:top_logprobs] ||= top_logprobs.presence
params[:top_p] ||= top_p.presence
if json
params[:provider] ||= {}
params[:provider][:require_parameters] = true
params[:response_format] ||= {}
params[:response_format][:type] = "json_object"
end
# set the model to the default if not provided
self.model ||= Raix.configuration.model
begin
response = if openai
openai_request(params:, model: openai,
messages:)
else
openrouter_request(
params:, model:, messages:
)
end
retry_count = 0
content = nil
# no need for additional processing if streaming
return if stream && response.blank?
# tuck the full response into a thread local in case needed
Thread.current[:chat_completion_response] = response.with_indifferent_access
# TODO: add a standardized callback hook for usage events
# broadcast(:usage_event, usage_subject, self.class.name.to_s, response, premium?)
# TODO: handle parallel tool calls
if (function = response.dig("choices", 0, "message", "tool_calls", 0, "function"))
@current_function = function["name"]
# dispatch the called function
arguments = JSON.parse(function["arguments"].presence || "{}")
arguments[:bot_message] = bot_message if respond_to?(:bot_message)
return send(function["name"], arguments.with_indifferent_access)
end
response.tap do |res|
content = res.dig("choices", 0, "message", "content")
if json
content = content.squish
return JSON.parse(content)
end
return content unless raw
end
rescue JSON::ParserError => e
if e.message.include?("not a valid") # blank JSON
puts "Retrying blank JSON response... (#{retry_count} attempts) #{e.message}"
retry_count += 1
sleep 1 * retry_count # backoff
retry if retry_count < 3
raise e # just fail if we can't get content after 3 attempts
end
# attempt to fix the JSON
JsonFixer.new.call(content, e.message)
rescue Faraday::BadRequestError => e
# make sure we see the actual error message on console or Honeybadger
puts "Chat completion failed!!!!!!!!!!!!!!!!: #{e.response[:body]}"
raise e
end
end
# This method returns the transcript array.
# Manually add your messages to it in the following abbreviated format
# before calling `chat_completion`.
#
# { system: "You are a pumpkin" },
# { user: "Hey what time is it?" },
# { assistant: "Sorry, pumpkins do not wear watches" }
#
# to add a function result use the following format:
# { function: result, name: 'fancy_pants_function' }
#
# @return [Array] The transcript array.
def transcript
@transcript ||= []
end
private
def openai_request(params:, model:, messages:)
params[:stream] ||= stream.presence
Raix.configuration.openai_client.chat(parameters: params.compact.merge(model:, messages:))
end
def openrouter_request(params:, model:, messages:)
retry_count = 0
begin
Raix.configuration.openrouter_client.complete(messages, model:, extras: params.compact, stream:)
rescue OpenRouter::ServerError => e
if e.message.include?("retry")
puts "Retrying OpenRouter request... (#{retry_count} attempts) #{e.message}"
retry_count += 1
sleep 1 * retry_count # backoff
retry if retry_count < 5
end
raise e
end
end
def transform_message_format(message)
return message if message[:role].present?
if message[:function].present?
{ role: "assistant", name: message.dig(:function, :name), content: message.dig(:function, :arguments).to_json }
elsif message[:result].present?
{ role: "function", name: message[:name], content: message[:result] }
else
{ role: message.first.first, content: message.first.last }
end
end
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/lib/raix/function_dispatch.rb | lib/raix/function_dispatch.rb | # frozen_string_literal: true
require "securerandom"
module Raix
# Provides declarative function definition for ChatCompletion classes.
#
# Example:
#
# class MeaningOfLife
# include Raix::ChatCompletion
# include Raix::FunctionDispatch
#
# function :ask_deep_thought do
# wait 236_682_000_000_000
# "The meaning of life is 42"
# end
#
# def initialize
# transcript << { user: "What is the meaning of life?" }
# chat_completion
# end
# end
module FunctionDispatch
extend ActiveSupport::Concern
class_methods do
attr_reader :functions
# Defines a function that can be dispatched by the ChatCompletion module while
# processing the response from an AI model.
#
# Declaring a function here will automatically add it (in JSON Schema format) to
# the list of tools provided to the OpenRouter Chat Completion API. The function
# will be dispatched by name, so make sure the name is unique. The function's block
# argument will be executed in the instance context of the class that includes this module.
#
# Example:
# function :google_search, description: "Search Google for something", query: { type: "string" } do |arguments|
# GoogleSearch.new(arguments[:query]).search
# end
#
# @param name [Symbol] The name of the function.
# @param description [String] An optional description of the function.
# @param parameters [Hash] The parameters that the function accepts.
# @param block [Proc] The block of code to execute when the function is called.
def function(name, description = nil, **parameters, &block)
@functions ||= []
@functions << begin
{ name:, parameters: { type: "object", properties: {} } }.tap do |definition|
definition[:description] = description if description.present?
parameters.map do |key, value|
definition[:parameters][:properties][key] = value
end
end
end
define_method(name) do |arguments|
id = SecureRandom.uuid[0, 23]
transcript << {
role: "assistant",
content: nil,
tool_calls: [
{
id:,
type: "function",
function: {
name:,
arguments: arguments.to_json
}
}
]
}
instance_exec(arguments, &block).tap do |content|
transcript << {
role: "tool",
tool_call_id: id,
name:,
content: content.to_s
}
# TODO: add on_error handler as optional parameter to function
end
chat_completion(**chat_completion_args) if loop
end
end
end
included do
attr_accessor :chat_completion_args
end
def chat_completion(**chat_completion_args)
raise "No functions defined" if self.class.functions.blank?
self.chat_completion_args = chat_completion_args
super
end
# Stops the looping of chat completion after function calls.
# Useful for manually halting processing in workflow components
# that do not require a final text response to an end user.
def stop_looping!
self.loop = false
end
def tools
self.class.functions.map { |function| { type: "function", function: } }
end
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
OlympiaAI/raix-rails | https://github.com/OlympiaAI/raix-rails/blob/c3f21ece8921bef080199073aea30bf504e74689/lib/raix/rails/version.rb | lib/raix/rails/version.rb | # frozen_string_literal: true
module Raix
module Rails
VERSION = "0.3.1"
end
end
| ruby | MIT | c3f21ece8921bef080199073aea30bf504e74689 | 2026-01-04T17:45:38.241281Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/helpers/home_helper.rb | app/helpers/home_helper.rb | module HomeHelper
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/controllers/home_controller.rb | app/controllers/home_controller.rb | class HomeController < ApplicationController
before_filter :login_required#, :except => :index
def index
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/controllers/user_sessions_controller.rb | app/controllers/user_sessions_controller.rb | class UserSessionsController < ApplicationController
before_filter :login_required, :only => [ :destroy ]
respond_to :html
# omniauth callback method
def create
omniauth = env['omniauth.auth']
logger.debug "+++ #{omniauth}"
user = User.find_by_uid(omniauth['uid'])
if not user
# New user registration
user = User.new(:uid => omniauth['uid'])
end
user.first_name = omniauth['extra']['first_name']
user.last_name = omniauth['extra']['last_name']
user.save
#p omniauth
# Currently storing all the info
session[:user_id] = omniauth
flash[:notice] = "Successfully logged in"
redirect_to root_path
end
# Omniauth failure callback
def failure
flash[:notice] = params[:message]
end
# logout - Clear our rack session BUT essentially redirect to the provider
# to clean up the Devise session from there too !
def destroy
session[:user_id] = nil
flash[:notice] = 'You have successfully signed out!'
redirect_to "#{CUSTOM_PROVIDER_URL}/users/sign_out"
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
def login_required
if !current_user
respond_to do |format|
format.html {
redirect_to '/auth/joshid'
}
format.json {
render :json => { 'error' => 'Access Denied' }.to_json
}
end
end
end
def current_user
return nil unless session[:user_id]
@current_user ||= User.find_by_uid(session[:user_id]['uid'])
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/app/models/user.rb | app/models/user.rb | class User < ActiveRecord::Base
attr_accessible :uid, :first_name, :last_name
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/db/seeds.rb | db/seeds.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/db/schema.rb | db/schema.rb | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20101007212537) do
create_table "users", :force => true do |t|
t.string "uid"
t.string "first_name"
t.string "last_name"
t.string "status"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/db/migrate/20101007212537_create_users.rb | db/migrate/20101007212537_create_users.rb | class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :uid
t.string :first_name
t.string :last_name
t.string :status
t.timestamps
end
end
def self.down
drop_table :users
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/test/test_helper.rb | test/test_helper.rb | ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/test/performance/browsing_test.rb | test/performance/browsing_test.rb | require 'test_helper'
require 'rails/performance_test_help'
class BrowsingTest < ActionDispatch::PerformanceTest
# Refer to the documentation for all available options
# self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
# :output => 'tmp/performance', :formats => [:flat] }
def test_homepage
get '/'
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/lib/josh_id.rb | lib/josh_id.rb | require 'omniauth-oauth2'
module OmniAuth
module Strategies
class JoshId < OmniAuth::Strategies::OAuth2
CUSTOM_PROVIDER_URL = 'http://localhost:3000'
option :client_options, {
:site => CUSTOM_PROVIDER_URL,
:authorize_url => "#{CUSTOM_PROVIDER_URL}/auth/josh_id/authorize",
:access_token_url => "#{CUSTOM_PROVIDER_URL}/auth/josh_id/access_token"
}
uid { raw_info['id'] }
info do
{
:email => raw_info['email']
}
end
extra do
{
:first_name => raw_info['extra']['first_name'],
:last_name => raw_info['extra']['last_name']
}
end
def raw_info
@raw_info ||= access_token.get("/auth/josh_id/user.json?oauth_token=#{access_token.token}").parsed
end
end
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/application.rb | config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module OauthClientDemo
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/environment.rb | config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
require 'josh_id'
# Initialize the rails application
OauthClientDemo::Application.initialize!
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/routes.rb | config/routes.rb | OauthClientDemo::Application.routes.draw do
root :to => 'home#index'
# omniauth
match '/auth/:provider/callback', :to => 'user_sessions#create'
match '/auth/failure', :to => 'user_sessions#failure'
# Custom logout
match '/logout', :to => 'user_sessions#destroy'
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/boot.rb | config/boot.rb | require 'rubygems'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/session_store.rb | config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
OauthClientDemo::Application.config.session_store :cookie_store, key: '_oauth-client-demo_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# OauthClientDemo::Application.config.session_store :active_record_store
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/wrap_parameters.rb | config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/omniauth.rb | config/initializers/omniauth.rb | # Change this omniauth configuration to point to your registered provider
# Since this is a registered application, add the app id and secret here
APP_ID = 'YE0NYveQGoFsNLX220Dy5g'
APP_SECRET = 'aqpGBedDnHFyp5MmgT8KErr9D015ScmaY8r3vHg5C0'
CUSTOM_PROVIDER_URL = 'http://localhost:3000'
Rails.application.config.middleware.use OmniAuth::Builder do
provider :josh_id, APP_ID, APP_SECRET
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/inflections.rb | config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
#
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/initializers/secret_token.rb | config/initializers/secret_token.rb | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
OauthClientDemo::Application.config.secret_token = 'e076c49b76898f0657f93ae1f6790a07bb84c1f8fcf0e299e85d874df7ea301e66d96fb32fe2e204aa4a569588250b9f792794a79d7894a191f3ad6318ed6974'
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/environments/test.rb | config/environments/test.rb | OauthClientDemo::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/environments/development.rb | config/environments/development.rb | OauthClientDemo::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
joshsoftware/sso-devise-omniauth-client | https://github.com/joshsoftware/sso-devise-omniauth-client/blob/55d2c0ceb60adad839ad1fb821a12b1370437ea8/config/environments/production.rb | config/environments/production.rb | OauthClientDemo::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| ruby | MIT | 55d2c0ceb60adad839ad1fb821a12b1370437ea8 | 2026-01-04T17:45:40.365736Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/spec/spec_helper.rb | spec/spec_helper.rb | # well, really, no time for a lot of tests now
# dirty fast prototyping
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'hivemind'
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/spec/hivemind/vm_spec.rb | spec/hivemind/vm_spec.rb | require 'spec_helper'
module Hivemind
describe VM do
it 'should work for a program with a single number' do
vm = VM.new UniversalAST::Number.new(44)
expect(vm.run(Runtime::HivemindEnv).data[:_value]).to eq 44
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/spec/hivemind/universal_ast_spec.rb | spec/hivemind/universal_ast_spec.rb | require 'spec_helper'
module Hivemind
module UniversalAST
describe Element do
it 'fields initializes a class with given labels' do
class A < Element
fields :a
end
expect(A.new(2).a).to eq(2)
end
end
describe ModuleStatement do
it 'is initialized with an elements attribute' do
mod = ModuleStatement.new('ha', [])
expect(mod.elements).to eq([])
end
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/spec/hivemind/parser_spec.rb | spec/hivemind/parser_spec.rb | ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false | |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind.rb | lib/hivemind.rb | require_relative 'hivemind/universal_ast'
require_relative 'hivemind/environment'
require_relative 'hivemind/vm'
require_relative 'hivemind/runtime'
require_relative 'hivemind/syntax'
require_relative 'hivemind/renderer'
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/combinators.rb | lib/hivemind/combinators.rb | require_relative 'universal_ast'
class Combinator
def &(other)
And.new(self, other)
end
def |(other)
Or.new(self, other)
end
end
class Lit < Combinator
attr_reader :value
def initialize(value)
@value = value
end
def parse(input, refs)
if input.start_with?(@value)
[true, @value, input[@value.length.. -1]]
else
[false, '', input]
end
end
end
class Mat < Combinator
attr_reader :regex
def initialize(regex)
@regex = /\A#{regex}/
end
def parse(input, refs)
match = @regex.match(input)
if match
[true, input[0..match.to_s.size - 1], input[match.to_s.size.. -1]]
else
[false, '', input]
end
end
end
class Binary < Combinator
attr_accessor :first, :second
def initialize(first, second)
@first, @second = first, second
end
end
class And < Binary
def parse(input, refs)
first_success, first_result, remaining = @first.parse(input, refs)
if first_success
second_success, second_result, remaining = @second.parse(remaining, refs)
if second_success
return [true, combine(first_result, second_result), remaining]
end
end
[false, [], input]
end
def combine(first_result, second_result)
if @first.is_a?(And)
first_result + [second_result]
else
[first_result, second_result]
end
end
end
class Or < Binary
def parse(input, refs)
[@first, @second].each do |combinator|
success, result, remaining = combinator.parse(input, refs)
return [true, result, remaining] if success
end
[false, '', input]
end
end
class Many < Combinator
attr_accessor :parser
def initialize(parser, as: nil)
@parser = parser
end
def parse(input, refs)
success = true
remaining = input
results = []
while success
success, result, remaining = @parser.parse(remaining, refs)
results.push(result) if success
end
[true, results, remaining]
end
end
class Join < Combinator
attr_accessor :parser, :as
def initialize(parser, separator, as: nil)
@parser = parser
@separator = separator
@as = as.to_sym
@separator_parser = Lit.new(@separator) & Mat.new(/ */) #workaround hivemind
@@depth ||= 0
end
def parse(input, refs)
success = true
remaining = input
results = []
while success
# puts "#{' ' * @@depth}BEFORE " + @parser.label.to_s
# p [" " * @@depth, remaining]
# @@depth += 1
success, result, remaining = @parser.parse(remaining, refs)
# @@depth -= 1
# puts "#{' ' * @@depth}AFTER " + @parser.label.to_s
# p [" " * @@depth, success, remaining, results.length]
# puts
results.push(result) if success
if success
if remaining.start_with? ' (' # fix later
remaining = "\n#{remaining}"
end
success, result, remaining = @separator_parser.parse(remaining, refs)
end
end
[true, results, remaining]
end
end
class Ref < Combinator
attr_accessor :label
def initialize(label, as: nil)
@label = label
@as = as
end
def parse(input, refs)
ref_parser = refs[@label.to_sym]
ref_parser.parse(input, refs)
end
end
class Maybe < Combinator
attr_accessor :parser
def initialize(parser)
@parser = parser
end
def parse(input, refs)
_, result, remaining = @parser.parse(input, refs)
[true, result, remaining]
end
end
class Apply < Combinator
attr_accessor :parser
attr_reader :transformation
def initialize(parser, &transformation)
@parser, @transformation = parser, transformation
end
def parse(input, refs)
success, result, remaining = @parser.parse(input, refs)
result = @transformation.call(result) if success
[success, result, remaining]
end
end
def literal(value)
Literal.new(value)
end
def many(combinator)
Many.new(combinator)
end
def maybe(combinator)
Maybe.new(combinator)
end
def apply(combinator, &transformation)
Apply.new(combinator, &transformation)
end
def match(regex)
Match.new(regex)
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/syntax.rb | lib/hivemind/syntax.rb | require_relative 'combinators'
module Hivemind
# BaseGrammar = Phoenix::Grammar.new
# BaseGrammar.rules = {
# segment: many(ref(:keyword_structure), as: :elements),
# keyword_structure: ref(:module) | ref(:class) | ref(:method),
# method: lit('module') & some(ws) & ref(:name, as: :module_name) &
# many(ref(:expr), as: :body),
# expr: ref(:if) | ref(:sequence) | ref(:attribute) | ref(:attribute_assign) |
# ref(:assign) | ref(:literal),
# sequence: ref(:list) | ref(:dictionary),
# list: lit('[') & join(ref(:expr), ', ', as: :elements) & lit(']'),
# dictionary: lit('{') & join(ref(:pair), ', ', as: :elements) & lit('}'),
# pair: ref(:expr, as: :key) & some(ws) & '=>' & some(ws) & ref(:expr, as: :value),
# attribute: ref(:expr, as: :object, except: :attribute) & '.' & ref(:name, as: :label),
# attribute_assign: ref(:expr, as: :object, except: :attribute) & '.' & ref(:name, as: :label) & some(ws) & lit('=') & some(ws) & ref(:expr, as: :right),
# assign: ref(:name, as: :left) & some(ws) & lit('=') & some(ws) & ref(:expr, as: :right),
# literal: ref(:string) | ref(:boolean) | ref(:nil_literal) | ref(:number) | ref(:name)
# name: regex(/[a-zA-Z_]+/, as: :value),
# string: lit('"') & regex(/[^"]*/, as: :value) + lit('"'),
# number: regex(/[0-9]+(\.[0-9]+)?/, as: :value),
# boolean: ref(:true_literal) | ref(:false_literal),
# true_literal: 'true',
# false_literal: 'false',
# nil_literal: 'nil',
# :if => lit('if') & some(ws) & ref(:expr, as: :test) & lit(':') & nl & indent & join(ref(:expr), "\n", as: :true_branch) &
# nl & dedent & lit('else') & lit(':') & nl & indent & join(ref(:expr), "\n", as: :else_branch) & nl & dedent,
# :class => lit('class') & some(ws) & ref(:name, as: :class_name) &
# many(ref(:ex)
# }
TYPES = {
assign: {
left: :name,
right: :expr
},
attribute: {
object: :expr_no_attr,
label: :name_or_attr
},
image: {
statements: :class_statement
},
binary: {
left: :expr_no_binary,
operation: :operation,
right: :expr
},
attribute_assign: {
object: :expr_no_attr,
label: :name_or_attr,
right: :expr
},
call: {
function: :expr_no_call,
args: :expr
},
list: {
elements: :expr
},
dictionary: {
pair: :pair
},
pair: {
key: :string,
value: :expr
},
method_statement: {
method_name: :name,
args: :name,
body: :expr
},
class_statement: {
class_name: :name,
methods: :method_statement
},
module_statement: {
module_name: :name,
elements: :statement
},
if_statement: {
test: :expr,
true_branch: :expr,
else_branch: :expr
}
}
class Syntax
def self.generate_syntax(bidirectional_grammar)
new(bidirectional_grammar).generate
end
def initialize(grammar)
@grammar_source = grammar
end
def generate
# parse grammar
# combine into base grammar
rules = self.class.load_rules(@grammar_source)
refs = {}
rules.each do |name, rule|
refs[:"_#{name}"] = parse_rule rule, TYPES[name]
end
[REFS[:image], REFS.merge(refs)]
end
def parse_rule(rule, types)
parsers = []
tokens = []
token = ''
i = 0
while i < rule.length
z = rule[i]
if '<>'.include?(z)
tokens << token unless token.empty?
token = ''
if z == '>'
if rule[i + 1] == '>'
tokens << '>>'
i += 1
else
tokens << '>'
end
elsif z == '<'
if rule[i + 1] == '<'
tokens << '<<'
i += 1
else
tokens << '<'
end
end
elsif z == "'"
tokens << token unless token.empty?
token = ''
j = i
i += 1
while rule[i] != "'"
i += 1
end
tokens << rule[j..i]
elsif z == ' '
tokens << token unless token.empty?
token = ''
j = i
while rule[i] == ' '
i += 1
end
tokens << rule[j..i - 1]
i -= 1
elsif z == "\n"
tokens << token unless token.empty?
tokens << "\n"
elsif z.match /[a-zA-Z_0-9]/
token += z
else
tokens << token unless token.empty?
token = ''
tokens << z
end
i += 1
end
tokens << token unless token.empty?
r = 0
in_var = false
tokens.each_with_index do |token, i|
if token == '>>'
if tokens[i - 2] == ':'
parsers << Join.new(
Ref.new(types[tokens[i - 3].to_sym]),
tokens[i - 1][1..-2], as: tokens[i - 3])
else
parsers << Join.new(Ref.new(types[tokens[i - 1].to_sym]), "\n#{' ' * r}", as: tokens[i - 1])
#Many.new(Ref.new(types[tokens[i - 1].to_sym]), as: tokens[i - 1])
end
in_var = false
elsif token == '>'
parsers << Ref.new(types[tokens[i - 1].to_sym])
in_var = false
elsif token == "\n"
parsers << Ref.new(:nl)
if tokens[i + 1] == "\n"
e = 2
elsif tokens[i + 1]
match = tokens[i + 1].match /([ ]+)/
if match.nil? || match.captures.empty?
indent = 0
else
indent = match.captures.first.size / 4
end
if indent > r
parsers << Ref.new(:indent)
elsif indent < r
parsers << Ref.new(:dedent)
end
r = indent
end
elsif token.match(/\A +\z/)
parsers << Ref.new(:ws)
elsif (token == '<<' || token == '<') && tokens[i + 1] >= 'a' && tokens[i + 1] <= 'z'
in_var = true
elsif !in_var
parsers << Lit.new(token)
end
end
# parsers.map { |pa| puts pa.inspect }
parsers.reduce(:&)
end
def self.load_rules(grammar)
lines = grammar.split("\n")
rules = {}
current_rule = nil
rule_body = []
lines.each do |line|
if line.start_with? '#'
if not current_rule.nil?
rule_body << "\n" if rule_body.length > 1
rules[current_rule.to_sym] = rule_body.join("\n")
rule_body = []
end
current_rule = line[1..-1].strip
elsif line.strip != ''
rule_body << line
end
end
rule_body << "\n" if rule_body.length > 1
rules[current_rule.to_sym] = rule_body.join("\n")
rules
end
end
Name = UniversalAST::Name
Number = UniversalAST::Number
Assign = UniversalAST::Assign
Element = UniversalAST::Element
Call = UniversalAST::Call
List = UniversalAST::List
Dictionary = UniversalAST::Dictionary
Pair = UniversalAST::Pair
Attribute = UniversalAST::Attribute
AttributeAssign = UniversalAST::AttributeAssign
IfStatement = UniversalAST::IfStatement
MethodStatement = UniversalAST::MethodStatement
ClassStatement = UniversalAST::ClassStatement
Image = UniversalAST::Image
Operation = UniversalAST::Operation
Float = UniversalAST::Float
Int = UniversalAST::Int
REFS = {
name: Apply.new(Mat.new(/[a-zA-Z][a-zA-Z_]*/)) do |result|
Name.new(result.to_sym)
end,
image: Apply.new(Join.new(Ref.new(:class_statement), "", as: :statements)) do |children|
# d = children.select { |child| child.is_a?(MethodStatement) }
e = children.select { |child| child.is_a?(ClassStatement) }
# obj = e.find { |element| element.is_a?(ClassStatement) && element.class_name == :Object }
# p e[0].class_name
# if obj.nil? && !d.empty?
# obj = ClassStatement.new(Name.new(:Object), d)
# e << obj
# elsif obj
# obj.methods += d
# end
Image.new(e)
end,
statement: Ref.new(:module_statement) | Ref.new(:class_statement) | Ref.new(:method_statement),
number: Ref.new(:float) | Ref.new(:int),
float: Apply.new(Mat.new(/[0-9]+\.[0-9]+/)) do |result|
Float.new(result.to_f)
end,
int: Apply.new(Mat.new(/[0-9]+/)) do |result|
Int.new(result.to_i)
end,
string: Apply.new(Mat.new(/\"[^\"]*\"/)) do |result|
String.new(result[1..-2])
end,
ws: Mat.new(/ +/),
nl: Mat.new(/\n*/),
indent: Lit.new(''),
dedent: Lit.new(''),
expr: Ref.new(:attribute_assign) | Ref.new(:assign) | Ref.new(:binary) | Ref.new(:call) | Ref.new(:attribute) | Ref.new(:number) | Ref.new(:name) | Ref.new(:string),
expr_no_attr: Ref.new(:number) | Ref.new(:nil) | Ref.new(:name) | Ref.new(:string),
expr_no_call: Ref.new(:binary) | Ref.new(:attribute) | Ref.new(:number) | Ref.new(:name) | Ref.new(:string),
nil: Lit.new('nil'),
name_or_attr: Ref.new(:name) | Ref.new(:attribute),
assign: Apply.new(Ref.new(:_assign)) do |results|
Assign.new(*results.select { |r| r.is_a?(Element) })
end,
attribute_assign: Apply.new(Ref.new(:_attribute_assign)) do |results|
AttributeAssign.new(*results.select { |r| r.is_a?(Element) })
end,
call: Apply.new(Ref.new(:_call)) do |results|
function, args = results.select { |r| r.is_a?(Element) || r.is_a?(Array) }
Call.new(function, args)
end,
list: Apply.new(Ref.new(:_list)) do |results|
List.new(results[1])
end,
dictionary: Apply.new(Ref.new(:_dictionary)) do |results|
Dictionary.new(results[1])
end,
pair: Apply.new(Ref.new(:_pair)) do |results|
key, value = results.select { |r| r.is_a?(Element) }
Pair.new(key, value)
end,
binary: Apply.new(Ref.new(:_binary)) do |results|
if results[0].is_a?(String)
results = results[1..-1]
end
# detect operation intelligently
tokens = results[0], results[2], results[4]
if tokens[0].is_a?(UniversalAST::Operation)
operation, left, right = tokens
elsif tokens[1].is_a?(UniversalAST::Operation)
left, operation, right = tokens
else
left, right, operation = tokens
end
# p results
UniversalAST::Binary.new(left, operation, right)
end,
expr_no_binary: Ref.new(:attribute) | Ref.new(:number) | Ref.new(:name) | Ref.new(:string),
operation: Apply.new(Lit.new('+') | Lit.new('-') | Lit.new('**') | Lit.new('/') | Lit.new('*') | Lit.new('||')) do |result|
Operation.new(result)
end,
attribute: Apply.new(Ref.new(:_attribute)) do |results|
object, label = results.select { |r| r.is_a?(Element) }
Attribute.new(object, label)
end,
if_statement: Apply.new(Ref.new(:_if_statement)) do |results|
test, true_branch, else_branch = results.select { |r| r.is_a?(Element) || r.is_a?(Array) }
IfStatement.new(test, true_branch, else_branch)
end,
method_statement: Apply.new(Ref.new(:_method_statement)) do |results|
method_name, args, body = results.select { |r| r.is_a?(Element) || r.is_a?(Array) }
MethodStatement.new(method_name, args, body)
end,
class_statement: Apply.new(Ref.new(:_class_statement)) do |results|
class_name, methods = results.select { |r| r.is_a?(Element) || r.is_a?(Array) }
ClassStatement.new(class_name, methods)
end,
module_statement: Apply.new(Ref.new(:_module_statement)) do |results|
module_name, classes = results.select { |r| r.is_a?(Element) || r.is_a?(Array) }
ModuleStatement.new(module_name, classes)
end
}
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/environment.rb | lib/hivemind/environment.rb | require_relative 'errors'
module Hivemind
class Environment
attr_reader :parent, :values, :top
attr_accessor :current_self
def initialize(parent, **values)
@parent, @values, @top = parent, values, (parent.nil? ? values : parent.top)
end
def [](key)
value = fetch key
return value if value
raise HivemindMissingNameError.new("#{key} is missing")
end
def fetch(key)
current = self
until current.nil? || current.values.key?(key)
current = current.parent
end
return current.values[key] unless current.nil?
nil
end
def []=(key, value)
@values[key] = value
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/errors.rb | lib/hivemind/errors.rb | module Hivemind
class HivemindMissingNameError < StandardError
end
class HivemindAccessError < StandardError
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/vm.rb | lib/hivemind/vm.rb | require_relative 'runtime'
require_relative 'universal_ast'
module Hivemind
class VM
def initialize(ast)
@ast = ast
end
def run(env)
@ast.run env
end
end
class Runtime::HivemindObject
def call(function, args, env)
if function.is_a?(UniversalAST::MethodStatement)
args_values = {:self => self}
function.args[1..-1].zip(args) do |label, arg|
args_values[label.value.to_sym] = arg
end
body_env = Environment.new(env, **args_values)
function.body.map { |expr| expr.run(body_env) }[-1] || env.top[:@nil]
else
function.call self, *args, env
end
end
end
class Runtime::HivemindClass
def call(function, args, env)
h = Runtime::HivemindObject.new({}, self)
function = dispatch_method(:init)
if function.is_a?(UniversalAST::MethodStatement)
args_values = {:self => h}
function.args[1..-1].zip(args) do |label, arg|
args_values[label.value.to_sym] = arg
end
body_env = Environment.new(env, **args_values)
function.body.map { |expr| expr.run(body_env) }[-1] || env.top[:@nil]
else
function.call h, *args, env
end
h
end
end
module UniversalAST
class Image
def run(env)
@statements.each do |statement|
statement.run(env)
end
# puts env.top[:Object].methods.keys
if env.top[:Object].methods.key? :start
weird_object = Runtime::hivemind_object({})
weird_object.call(env.top[:Object].methods[:start], [], env)
else
env.top[:@nil]
end
end
end
class ModuleStatement
def run(env)
module_statement = Runtime::HivemindModule.new(@module_name)
@statements.each do |statement|
module_statement.elements[@statement.is_a?(ModuleStatement) ? @statement.module_name : @statement.class_name] =
statement.run(env)
end
env
end
end
class If
def run(env)
if @test.run(env) == env.top[:@true]
@true_branch.run env
else
@else_branch.run env
end
end
end
class Assign
def run(env)
env[@left.value.to_sym] = @right.run(env)
end
end
class Attribute
def run(env)
obj = @object.run(env)
env.current_self = obj
if obj.respond_to?(:data)
if obj.data.key? @label.value
obj.data[@label.value]
else
method = obj.klass.dispatch_method(@label.value)
if method
method
else
raise HivemindAccessError.new("No #{@label.value} in obj")
end
end
else
obj.methods[@label.value]
end
end
end
class AttributeAssign
def run(env)
@object.run(env).data[@label.value] = @right.run(env)
end
end
class Call
def run(env)
if !@function.is_a?(Attribute)
function = @function.run(env)
env.current_self.call(function, @args.map { |arg| arg.run(env) }, env)
elsif @function.label.value != :new
obj = @function.object.run(env)
function = obj.klass.dispatch_method(@function.label.value)
obj.call(function, @args.map { |arg| arg.run(env) }, env)
else
obj = @function.object.run(env)
function == obj.dispatch_method(:init)
obj.call(function, @args.map { |arg| arg.run(env) }, env)
end
end
end
class Binary
def run(env)
Runtime::hivemind_numbr(@left.run(env).data[:_value].send(@operation.value, @right.run(env).data[:_value]))
end
end
class List
def run(env)
Runtime::HivemindObject.new({_elements: @elements.map { |elem| elem.run(env) }}, env.top[:List])
end
end
class Dictionary
def run(env)
dict = {}
@pairs.each do |pair|
dict[pair.key.value.to_sym] = pair.value.run(env)
end
Runtime::HivemindObject.new({_dict: dict}, env.top[:Dict])
end
end
class Value
def run(env)
Runtime::HivemindObject.new({_value: @value}, env.top[self.class.name.split('::').last.to_sym])
end
end
class ClassStatement
def run(env)
definition = env.fetch(@class_name.value) || Runtime::HivemindClass.new(@class_name.value, env.top[:Object], {})
@methods.each do |method|
definition.methods[method.method_name.value] = method
end
env[@class_name.value] = definition
end
end
class MethodStatement
def run(env)
self
end
end
class Name
def run(env)
env[@value]
end
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/universal_ast.rb | lib/hivemind/universal_ast.rb | module Hivemind
module UniversalAST
class Element
def self.fields(*labels)
define_method(:initialize) do |*args|
args.zip(labels).each do |arg, label|
instance_variable_set "@#{label}", arg
end
end
attr_reader *labels
end
def offset(depth)
' ' * depth
end
end
class IfStatement < Element
# if <test>:
# <<true-branch>>
# else:
# <<else-branch>>
fields :test, :true_branch, :else_branch
def render(depth = 0)
"#{offset(depth)}If\n#{offset(depth + 1)}#{@test.render(depth + 1)}\n"
"#{@true_branch.render(depth + 1)}\n#{@else_branch.render(depth + 1)}\n"
end
end
class Assign < Element
# <left> = <right>
fields :left, :right
def render(depth = 0)
"#{offset(depth)}Assign left: #{@left.render} right: #{@right.render}"
end
end
class Attribute < Element
# <object>.<label>
fields :object, :label
def render(depth = 0)
"#{offset(depth)}Attribute : #{@object.render} #{@label.render}"
end
end
class AttributeAssign < Element
# <object>.<label> = <right>
fields :object, :label, :right
def render(depth = 0)
"#{offset(depth)}AttributeAssign : #{@object.render} #{@label.render} #{@right.render}"
end
end
class Call < Element
# <function>(<<args:', '>>)
fields :function, :args
def render(depth = 0)
"#{offset(depth)}Call\n#{@function.render(depth + 1)}\n#{offset(depth + 1)}#{@args.map(&:render).join(' ')}\n"
end
end
class List < Element
# [el1, el2..]
fields :elements
def render(depth = 0)
"#{offset(depth)}List\n#{@elements.map { |e| e.render(depth + 1) }.join("\n")}"
end
end
class Dictionary < Element
# {key1: val1, key2: val2..}
fields :pairs
end
class Binary < Element
# <left> <operation> <right>
fields :left, :operation, :right
def render(depth = 0)
"#{offset(depth)}Binary #{@left.render} #{@operation.value} #{@right.render}"
end
end
class MethodStatement < Element
# method <method-name>(<<args:', '):
# <<body>>
fields :method_name, :args, :body
def render(depth = 0)
"#{offset(depth)}MethodStatement #{@method_name.value} #{@args.map(&:render).join(' ')}\n" +
"#{@body.map { |e| e.render(depth + 1) }.join("\n")}\n"
end
end
class ClassStatement < Element
# type <class-name>:
# <<methods>>
fields :class_name, :methods
def render(depth = 0)
"#{offset(depth)}ClassStatement #{@class_name.value}\n" +
"#{@methods.map { |e| e.render(depth + 1) }.join("\n")}\n"
end
end
class Value < Element
fields :value
def render(depth = 0)
"#{offset(depth)}#{@value}"
end
end
class Name < Value
end
class String < Value
end
class Number < Value
end
class Int < Number
end
class Float < Number
end
class Operation < Value
end
class ModuleStatement < Element
# module <module-name>:
# <<children>>
fields :module_name, :elements
end
class Pair < Element
# key => value
fields :key, :value
end
class Image < Element
fields :statements
def render(depth = 0)
@statements.map(&:render).join "\n"
end
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/code_viewer.rb | lib/hivemind/code_viewer.rb | # 'universal_ast'
# module Hivemind
# class CodeViewer
# def initialize(tree)
# @tree = tree
# end
# def view_as(query)
# hierarchy = QueryAnalyzer.parse(query)
# rebuild_tree(hierarchy)
# end
# def rebuild_tree(hierarchy)
# if hierarchy[0].type == @code_view.hierarchy[0].type
# # only sorting maybe
# # and sorting still not supported
# @tree
# else
# # method > code
# new_tree = UniversalAST::Image.new([])
# top = {}
# if hierarchy[0].type == :method
# @tree.statements.each do |statement|
# statement.methods.each do |method|
# top[method.method_name.value] ||= {}
# top[method.method_name.value][statement.class_name.value] = [args, method.body]
# end
# end
# else
# @tree.statements.each do |statement|
# statement.body.each do |method|
# top[method.class_name.value] ||= {}
# top[method.class_name.value][statement.method_name.value] = [args, method.body]
# end
# end
# end
# end
# end
# end
# end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/runtime.rb | lib/hivemind/runtime.rb | require_relative 'environment'
module Hivemind
module Runtime
class HivemindObject
attr_reader :data, :klass
def initialize(data, klass)
@data, @klass = data, klass
end
end
class HivemindClass
attr_reader :label, :methods, :parent
def initialize(label, parent = nil, methods = {})
@label, @parent, @methods = label, parent, methods
end
def define_hivemind_method(label, &handler)
@methods[label] = handler
end
def dispatch_method(label)
current = self
until current.nil? || current.methods.key?(label)
current = current.parent
end
!current ? nil : current.methods[label]
end
end
class HivemindModule
attr_reader :label, :elements
def initialize(label, elements = [])
@elements = elements
end
end
def self.hivemind_string(value)
HivemindObject.new({_value: value}, HivemindEnv[:String])
end
def self.hivemind_numbr(value)
HivemindObject.new({_value: value}, HivemindEnv[value.is_a?(Fixnum) ? :Int : :Float])
end
def self.hivemind_object(data)
HivemindObject.new(data, HivemindEnv[:Object])
end
HivemindEnv = Environment.new(nil,
Object: HivemindClass.new('Object')
)
HivemindEnv[:Class] = HivemindClass.new('Class', HivemindEnv[:Object])
HivemindEnv[:String] = HivemindClass.new('String', HivemindEnv[:Object])
HivemindEnv[:Int] = HivemindClass.new('Int', HivemindEnv[:Object])
HivemindEnv[:Float] = HivemindClass.new('Float', HivemindEnv[:Object])
HivemindEnv[:Boolean] = HivemindClass.new('Boolean', HivemindEnv[:Object])
HivemindEnv[:@true] = HivemindObject.new({}, HivemindEnv[:Boolean])
HivemindEnv[:NilClass] = HivemindClass.new('NilClass', HivemindEnv[:Object])
HivemindEnv[:@nil] = HivemindObject.new({}, HivemindEnv[:NilClass])
HivemindEnv[:Object].define_hivemind_method(:display) do |hivemind_self, *args, env|
puts hivemind_self.call(hivemind_self.klass.dispatch_method(:to_string), args, env).data[:_value]
end
HivemindEnv[:Object].define_hivemind_method(:to_string) do |hivemind_self, *args, env|
# p hivemind_self
if [HivemindEnv[:Int], HivemindEnv[:Float], HivemindEnv[:String], HivemindEnv[:Boolean]].include? hivemind_self.klass
hivemind_string(hivemind_self.data[:_value])
elsif hivemind_self.klass == HivemindEnv[:NilClass]
hivemind_string('null')
else
y = ''
i = 0
y2 = []
hivemind_self.data.each do |key, value|
y2 << key.to_s + ':' + value.call(value.klass.dispatch_method(:to_string), [], env).data[:_value].to_s
end
y = y2.join(', ')
hivemind_string("{#{y}}")
end
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
alehander92/hivemind | https://github.com/alehander92/hivemind/blob/8a0727078b566b5dbfffcc2e97465e4132092a47/lib/hivemind/renderer.rb | lib/hivemind/renderer.rb | require_relative 'syntax'
module Hivemind
BASE_RULES = {
image: -> element, depth = 0 do
element.statements.map { |s| render_element(s) }.join("\n")
end,
int: -> element, depth = 0 do
element.value.to_s
end,
float: -> element, depth = 0 do
element.value.to_s
end,
string: -> element, depth = 0 do
'"' + element.value.to_s + '"'
end,
name: -> element, depth = 0 do
element.value.to_s
end,
operation: -> element, depth = 0 do
element.value.to_s
end
}
class Renderer
def initialize(tree, syntax)
@tree, @syntax = tree, syntax
@rules = BASE_RULES.merge(Syntax.load_rules(syntax))
end
def render(depth = 0)
render_element(@tree, depth).gsub(/\n\n+/, "\n\n").gsub(/\)\s+\)/, '))').gsub(/\}\s+\}/, '}}')
end
def offset(depth = 0)
' ' * depth
end
def render_element(element, depth = 0)
rule = @rules[element.class.name.split('::').last.downcase.gsub('attributeassign', 'attribute_assign').gsub('statement', '_statement').to_sym]
depth += 1 if element.class.name.end_with?('MethodStatement')
# p "for #{element.class.name.split('::').last.downcase.gsub('statement', '_statement').to_sym} #{depth}"
offset(depth) + if rule.is_a?(String)
render_template rule, element, depth
elsif rule.is_a?(Proc)
instance_exec element, depth, &rule
end
end
def render_template(plan, element, depth = 0)
plan = plan.gsub(/\<\<([a-zA-Z_]+)\:'([^\']*)'\>\>/) do
element.send(Regexp.last_match[1]).map(&method(:render_element)).join(Regexp.last_match[2])
end
# p plan
plan = plan.gsub(/\<\<([a-zA-Z_]+)\>\>/) do
element.send(Regexp.last_match[1]).map { |e| render_element(e, depth) }.join("\n")
end
p plan
plan = plan.gsub(/\<([a-zA-Z_]+)\>/) do
render_element(element.send(Regexp.last_match[1]))
end
plan
end
end
end
| ruby | MIT | 8a0727078b566b5dbfffcc2e97465e4132092a47 | 2026-01-04T17:45:40.296119Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/guest_spec.rb | spec/guest_spec.rb | require 'vagrant-alpine/guest'
require 'vagrant-alpine/plugin'
require 'vagrant-alpine/cap/change_host_name'
require 'vagrant-alpine/cap/configure_networks'
require 'vagrant-alpine/cap/halt'
require 'vagrant-alpine/cap/rsync'
require 'vagrant-alpine/cap/nfs_client'
describe VagrantPlugins::GuestAlpine::Plugin do
it 'should be loaded with alpine' do
expect(described_class.components.guests[:alpine].first).to eq(VagrantPlugins::GuestAlpine::Guest)
end
{
change_host_name: VagrantPlugins::GuestAlpine::Cap::ChangeHostName,
configure_networks: VagrantPlugins::GuestAlpine::Cap::ConfigureNetworks,
halt: VagrantPlugins::GuestAlpine::Cap::Halt,
rsync_installed: VagrantPlugins::GuestAlpine::Cap::RSync,
rsync_install: VagrantPlugins::GuestAlpine::Cap::RSync,
nfs_client_install: VagrantPlugins::GuestAlpine::Cap::NFSClient
}.each do |cap, cls|
it "should be capable of #{cap} with alpine" do
expect(described_class.components.guest_capabilities[:alpine][cap])
.to eq(cls)
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/spec_helper.rb | spec/spec_helper.rb | require 'vagrant'
require 'support/dummy_communicator'
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/support/dummy_communicator.rb | spec/support/dummy_communicator.rb | module VagrantTests
module DummyCommunicator
class Communicator < Vagrant.plugin("2", :communicator)
def ready?
true
end
attr_reader :known_commands
def initialize(machine)
@known_commands = Hash.new do |hash, key|
hash[key] = { expected: 0, received: 0, response: nil }
end
end
def expected_commands
known_commands.select do |command, info|
info[:expected] > 0
end
end
def received_commands
known_commands.select do |command, info|
info[:received] > 0
end.keys
end
def stub_command(command, response)
known_commands[command][:response] = response
end
def expect_command(command)
known_commands[command][:expected] += 1
end
def received_summary
received_commands.map { |cmd| " - #{cmd}" }.unshift('received:').join("\n")
end
def verify_expectations!
expected_commands.each do |command, info|
if info[:expected] != info[:received]
fail([
"expected to receive '#{command}' #{info[:expected]} times",
"got #{info[:received]} times instead",
received_summary
].join("\n"))
end
end
end
def execute(command, opts=nil)
known = known_commands[command]
known[:received] += 1
response = known[:response]
return unless response
if block_given?
[:stdout, :stderr].each do |type|
Array(response[type]).each do |line|
yield type, line
end
end
end
if response[:raise]
raise response[:raise]
end
response[:exit_code]
end
def sudo(command, opts=nil, &block)
execute(command, opts, &block)
end
def test(command, opts=nil)
execute(command, opts) == 0
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/cap/halt_spec.rb | spec/cap/halt_spec.rb |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::Halt' do
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:halt)
end
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
it 'should halt guest' do
expect(communicator).to receive(:sudo).with('poweroff')
allow_message_expectations_on_nil
described_class.halt(machine)
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/cap/configure_networks_spec.rb | spec/cap/configure_networks_spec.rb |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::ConfigureNetworks' do
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:configure_networks)
end
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
it 'should configure networks' do
networks = [
{ type: :static, ip: '192.168.10.10', netmask: '255.255.255.0', interface: 0, name: 'eth0' },
{ type: :dhcp, interface: 1, name: 'eth1' }
]
expect(communicator).to receive(:sudo).with("sed -e '/^#VAGRANT-BEGIN/,$ d' /etc/network/interfaces > /tmp/vagrant-network-interfaces.pre")
expect(communicator).to receive(:sudo).with("sed -ne '/^#VAGRANT-END/,$ p' /etc/network/interfaces | tail -n +2 > /tmp/vagrant-network-interfaces.post")
expect(communicator).to receive(:sudo).with('/sbin/ifdown eth0 2> /dev/null')
expect(communicator).to receive(:sudo).with('/sbin/ip addr flush dev eth0 2> /dev/null')
expect(communicator).to receive(:sudo).with('/sbin/ifdown eth1 2> /dev/null')
expect(communicator).to receive(:sudo).with('/sbin/ip addr flush dev eth1 2> /dev/null')
expect(communicator).to receive(:sudo).with('cat /tmp/vagrant-network-interfaces.pre /tmp/vagrant-network-entry /tmp/vagrant-network-interfaces.post > /etc/network/interfaces')
expect(communicator).to receive(:sudo).with('rm -f /tmp/vagrant-network-interfaces.pre /tmp/vagrant-network-entry /tmp/vagrant-network-interfaces.post')
expect(communicator).to receive(:sudo).with('/sbin/ifup eth0')
expect(communicator).to receive(:sudo).with('/sbin/ifup eth1')
allow_message_expectations_on_nil
described_class.configure_networks(machine, networks)
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/cap/change_host_name_spec.rb | spec/cap/change_host_name_spec.rb |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::ChangeHostname' do
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:change_host_name)
end
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
let(:old_hostname) { 'oldhostname.olddomain.tld' }
before do
allow(machine).to receive(:communicate).and_return(communicator)
communicator.stub_command('hostname -f', stdout: old_hostname)
end
after do
communicator.verify_expectations!
end
describe '.change_host_name' do
it 'updates /etc/hostname on the machine' do
communicator.expect_command("echo 'newhostname' > /etc/hostname")
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
it 'does nothing when the provided hostname is not different' do
described_class.change_host_name(machine, 'oldhostname.olddomain.tld')
expect(communicator.received_commands).to eq(['hostname -f'])
end
it 'refreshes the hostname service with the hostname command' do
communicator.expect_command('hostname -F /etc/hostname')
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
it 'renews dhcp on the system with the new hostname' do
communicator.expect_command('ifdown -a; ifup -a; ifup eth0')
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
describe 'flipping out the old hostname in /etc/hosts' do
let(:sed_command) do
# Here we run the change_host_name through and extract the recorded sed
# command from the dummy communicator
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
communicator.received_commands.find { |cmd| cmd =~ /^sed/ }
end
# Now we extract the regexp from that sed command so we can do some
# verification on it
let(:expression) { sed_command.sub(%r{^sed -ri '\(.*\)' /etc/hosts$}, "\1") }
let(:search) { Regexp.new(expression.split('@')[1], Regexp::EXTENDED) }
let(:replace) { expression.split('@')[2] }
let(:grep_command) { "grep '#{old_hostname}' /etc/hosts" }
before do
communicator.stub_command(grep_command, exit_code: 0)
end
it 'works on an simple /etc/hosts file' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.olddomain.tld oldhostname
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
RESULT
end
it 'does not modify lines which contain similar hostnames' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.olddomain.tld oldhostname
# common prefix, but different fqdn
192.168.12.34 oldhostname.olddomain.tld.different
# different characters at the dot
192.168.34.56 oldhostname-olddomain.tld
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
# common prefix, but different fqdn
192.168.12.34 oldhostname.olddomain.tld.different
# different characters at the dot
192.168.34.56 oldhostname-olddomain.tld
RESULT
end
it "appends 127.0.1.1 if it isn't there" do
communicator.stub_command(grep_command, exit_code: 1)
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
sed = communicator.received_commands.find { |cmd| cmd =~ /^sed/ }
expect(sed).to be_nil
echo = communicator.received_commands.find { |cmd| cmd =~ /^echo/ }
expect(echo).to_not be_nil
end
context 'when the old fqdn has a trailing dot' do
let(:old_hostname) { 'oldhostname.withtrailing.dot.' }
it 'modifies /etc/hosts properly' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.withtrailing.dot. oldhostname
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
RESULT
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/cap/nfs_client_spec.rb | spec/cap/nfs_client_spec.rb |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::NFSClient' do
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:nfs_client_install)
end
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
it 'should install nfs client' do
x = <<-EOS.gsub(/^\s+\|\s?/, '')
| # work around defunct repository in configuration
| # box: maier/apline-3.3
| repo_file="/etc/apk/repositories"
| if [ $(grep -c "repos.dfw.lax-noc.com" $repo_file) -ne 0 ]; then
| repo_file_bak="${repo_file}.orig"
| echo "updating repositories"
| cp $repo_file $repo_file_bak
| sed -e 's/repos.dfw.lax-noc.com/dl-cdn.alpinelinux.org/' $repo_file_bak > $repo_file
| fi
|
| echo "updating repository indices"
| apk update
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "installing nfs-utils"
| apk add --upgrade nfs-utils
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "installing rpc.statd"
| rc-update add rpc.statd
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "starting rpc.statd service"
| rc-service rpc.statd start
| if [ $? -ne 0 ]; then
| exit 1
| fi
EOS
expect(communicator).to receive(:sudo).with(x)
allow_message_expectations_on_nil
described_class.nfs_client_install(machine)
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/spec/cap/rsync_spec.rb | spec/cap/rsync_spec.rb |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::RSync' do
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:rsync_install)
end
it 'should install rsync' do
# communicator.should_receive(:sudo).with('apk add rsync')
expect(communicator).to receive(:sudo).with('apk add rsync')
allow_message_expectations_on_nil
described_class.rsync_install(machine)
end
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:rsync_installed)
end
it 'should verify rsync installed' do
# communicator.should_receive(:test).with('test -f /usr/bin/rsync')
expect(communicator).to receive(:test).with('test -f /usr/bin/rsync')
allow_message_expectations_on_nil
described_class.rsync_installed(machine)
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine.rb | lib/vagrant-alpine.rb | # rubocop:disable Style/FileName
#
# squelch:
# lib/vagrant-alpine.rb:1:1: C: Use snake_case for source file names.
# require 'pathname'
#
require 'pathname'
require 'vagrant-alpine/plugin'
module VagrantPlugins
module GuestAlpine
# lib_path = Pathname.new(File.expand_path('../vagrant-alpine', __FILE__))
# autoload :Action, lib_path.join('action')
# autoload :Errors, lib_path.join('errors')
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/version.rb | lib/vagrant-alpine/version.rb | module VagrantPlugins
# Alpine Linux guest gem + plugin version
module GuestAlpine
VERSION = '0.4.0'
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/plugin.rb | lib/vagrant-alpine/plugin.rb | begin
require 'vagrant'
rescue LoadError
raise 'The Vagrant Alpine Linux Guest plugin must be run within Vagrant.'
end
if Vagrant::VERSION < '1.7.0'
fail 'The vagrant-alpine plugin is only compatible with Vagrant 1.7+'
end
module VagrantPlugins
module GuestAlpine
class Plugin < Vagrant.plugin('2')
name 'Alpine guest'
description 'Alpine Linux guest support.'
guest('alpine', 'linux') do
require File.expand_path('../guest', __FILE__)
Guest
end
guest_capability('alpine', 'configure_networks') do
require_relative 'cap/configure_networks'
Cap::ConfigureNetworks
end
guest_capability('alpine', 'halt') do
require_relative 'cap/halt'
Cap::Halt
end
guest_capability('alpine', 'change_host_name') do
require_relative 'cap/change_host_name'
Cap::ChangeHostName
end
guest_capability('alpine', 'nfs_client_install') do
require_relative 'cap/nfs_client'
Cap::NFSClient
end
guest_capability('alpine', 'rsync_installed') do
require_relative 'cap/rsync'
Cap::RSync
end
guest_capability('alpine', 'rsync_install') do
require_relative 'cap/rsync'
Cap::RSync
end
guest_capability('alpine', 'smb_install') do
require_relative 'cap/smb'
Cap::SMB
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/guest.rb | lib/vagrant-alpine/guest.rb | begin
require 'vagrant'
rescue LoadError
raise 'The Vagrant Alpine Linux Guest plugin must be run within Vagrant.'
end
if Vagrant::VERSION < '1.7.0'
fail 'The vagrant-alpine plugin is only compatible with Vagrant 1.7+'
end
module VagrantPlugins
module GuestAlpine
class Guest < Vagrant.plugin('2', :guest)
def detect?(machine)
machine.communicate.test('cat /etc/alpine-release')
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/rsync.rb | lib/vagrant-alpine/cap/rsync.rb | module VagrantPlugins
module GuestAlpine
module Cap
class RSync
def self.rsync_installed(machine)
machine.communicate.test('test -f /usr/bin/rsync')
end
def self.rsync_install(machine)
machine.communicate.tap do |comm|
comm.sudo('apk add rsync')
end
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/halt.rb | lib/vagrant-alpine/cap/halt.rb | # rubocop:disable Style/RedundantBegin
# rubocop:disable Lint/HandleExceptions
#
# FIXME: address disabled warnings
#
module VagrantPlugins
module GuestAlpine
module Cap
class Halt
def self.halt(machine)
begin
machine.communicate.sudo('poweroff')
rescue Net::SSH::Disconnect, IOError
# Ignore, this probably means connection closed because it
# shut down and SSHd was stopped.
end
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/configure_networks.rb | lib/vagrant-alpine/cap/configure_networks.rb | # rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/BracesAroundHashParameters
#
# FIXME: address disabled warnings
#
require 'set'
require 'tempfile'
require 'pathname'
require 'vagrant/util/template_renderer'
module VagrantPlugins
module GuestAlpine
module Cap
class ConfigureNetworks
def self.source_root
@source_root ||= Pathname.new(File.expand_path('../../../../', __FILE__))
end
include Vagrant::Util
def self.configure_networks(machine, networks)
machine.communicate.tap do |comm|
# First, remove any previous network modifications
# from the interface file.
comm.sudo("sed -e '/^#VAGRANT-BEGIN/,$ d' /etc/network/interfaces > /tmp/vagrant-network-interfaces.pre")
comm.sudo("sed -ne '/^#VAGRANT-END/,$ p' /etc/network/interfaces | tail -n +2 > /tmp/vagrant-network-interfaces.post")
# Accumulate the configurations to add to the interfaces file as
# well as what interfaces we're actually configuring since we use that
# later.
interfaces = Set.new
entries = []
networks.each do |network|
interfaces.add(network[:interface])
entry = TemplateRenderer.render("guests/alpine/network_#{network[:type]}", { options: network, template_root: source_root.join('templates') })
entries << entry
end
# Perform the careful dance necessary to reconfigure
# the network interfaces
temp = Tempfile.new('vagrant')
temp.binmode
temp.write(entries.join("\n"))
temp.close
comm.upload(temp.path, '/tmp/vagrant-network-entry')
# Bring down all the interfaces we're reconfiguring. By bringing down
# each specifically, we avoid reconfiguring eth0 (the NAT interface) so
# SSH never dies.
interfaces.each do |interface|
comm.sudo("/sbin/ifdown eth#{interface} 2> /dev/null")
comm.sudo("/sbin/ip addr flush dev eth#{interface} 2> /dev/null")
end
comm.sudo('cat /tmp/vagrant-network-interfaces.pre /tmp/vagrant-network-entry /tmp/vagrant-network-interfaces.post > /etc/network/interfaces')
comm.sudo('rm -f /tmp/vagrant-network-interfaces.pre /tmp/vagrant-network-entry /tmp/vagrant-network-interfaces.post')
# Bring back up each network interface, reconfigured
interfaces.each do |interface|
comm.sudo("/sbin/ifup eth#{interface}")
end
end
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/change_host_name.rb | lib/vagrant-alpine/cap/change_host_name.rb | module VagrantPlugins
module GuestAlpine
module Cap
class ChangeHostName
def self.change_host_name(machine, name)
new(machine, name).change!
end
attr_reader :machine, :new_hostname
def initialize(machine, new_hostname)
@machine = machine
@new_hostname = new_hostname
end
def change!
return unless should_change?
update_etc_hostname
update_etc_hosts
refresh_hostname_service
update_mailname
renew_dhcp
end
def should_change?
new_hostname != current_hostname
end
def current_hostname
@current_hostname ||= fetch_current_hostname
end
def fetch_current_hostname
hostname = ''
sudo 'hostname -f' do |type, data|
hostname = data.chomp if type == :stdout && hostname.empty?
end
hostname
end
def update_etc_hostname
sudo("echo '#{short_hostname}' > /etc/hostname")
end
# /etc/hosts should resemble:
# 127.0.0.1 localhost
# 127.0.1.1 host.fqdn.com host.fqdn host
def update_etc_hosts
if test("grep '#{current_hostname}' /etc/hosts")
# Current hostname entry is in /etc/hosts
ip_address = '([0-9]{1,3}\.){3}[0-9]{1,3}'
search = "^(#{ip_address})\\s+#{Regexp.escape(current_hostname)}(\\s.*)?$"
replace = "\\1 #{fqdn} #{short_hostname}"
expression = ['s', search, replace, 'g'].join('@')
sudo("sed -ri '#{expression}' /etc/hosts")
else
# Current hostname entry isn't in /etc/hosts, just append it
sudo("echo '127.0.1.1 #{fqdn} #{short_hostname}' >>/etc/hosts")
end
end
def refresh_hostname_service
sudo('hostname -F /etc/hostname')
end
def update_mailname
sudo('hostname -f > /etc/mailname')
end
def renew_dhcp
sudo('ifdown -a; ifup -a; ifup eth0')
end
def fqdn
new_hostname
end
def short_hostname
new_hostname.split('.').first
end
def sudo(cmd, &block)
machine.communicate.sudo(cmd, &block)
end
def test(cmd)
machine.communicate.test(cmd)
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/nfs_client.rb | lib/vagrant-alpine/cap/nfs_client.rb | module VagrantPlugins
module GuestAlpine
module Cap
class NFSClient
def self.nfs_client_install(machine)
comm = machine.communicate
comm.sudo <<-EOS.gsub(/^\s+\|\s?/, '')
| # work around defunct repository in configuration
| # box: maier/apline-3.3
| repo_file="/etc/apk/repositories"
| if [ $(grep -c "repos.dfw.lax-noc.com" $repo_file) -ne 0 ]; then
| repo_file_bak="${repo_file}.orig"
| echo "updating repositories"
| cp $repo_file $repo_file_bak
| sed -e 's/repos.dfw.lax-noc.com/dl-cdn.alpinelinux.org/' $repo_file_bak > $repo_file
| fi
|
| echo "updating repository indices"
| apk update
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "installing nfs-utils"
| apk add --upgrade nfs-utils
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "installing rpc.statd"
| rc-update add rpc.statd
| if [ $? -ne 0 ]; then
| exit 1
| fi
|
| echo "starting rpc.statd service"
| rc-service rpc.statd start
| if [ $? -ne 0 ]; then
| exit 1
| fi
EOS
end
end
end
end
end
| ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
maier/vagrant-alpine | https://github.com/maier/vagrant-alpine/blob/1cc9ec72c7438a5eba006369fba8fb8e53725f81/lib/vagrant-alpine/cap/smb.rb | lib/vagrant-alpine/cap/smb.rb | module VagrantPlugins
module GuestAlpine
module Cap
class SMB
def self.smb_install(machine)
machine.communicate.tap do |comm|
comm.sudo('apk add cifs-utils')
end
end
end
end
end
end | ruby | MIT | 1cc9ec72c7438a5eba006369fba8fb8e53725f81 | 2026-01-04T17:45:45.365621Z | false |
netlify/jekyll-srcset | https://github.com/netlify/jekyll-srcset/blob/ad7730dea2e3d4e03f8878e2b8fba8123cd06834/lib/jekyll-srcset.rb | lib/jekyll-srcset.rb | require "jekyll/srcset"
Liquid::Template.register_tag('image_tag', Jekyll::SrcsetTag)
| ruby | MIT | ad7730dea2e3d4e03f8878e2b8fba8123cd06834 | 2026-01-04T17:45:46.319190Z | false |
netlify/jekyll-srcset | https://github.com/netlify/jekyll-srcset/blob/ad7730dea2e3d4e03f8878e2b8fba8123cd06834/lib/jekyll/srcset.rb | lib/jekyll/srcset.rb | require "jekyll/srcset/version"
require "jekyll/srcset/tag"
require "jekyll"
module Jekyll
module Srcset
end
end
| ruby | MIT | ad7730dea2e3d4e03f8878e2b8fba8123cd06834 | 2026-01-04T17:45:46.319190Z | false |
netlify/jekyll-srcset | https://github.com/netlify/jekyll-srcset/blob/ad7730dea2e3d4e03f8878e2b8fba8123cd06834/lib/jekyll/srcset/tag.rb | lib/jekyll/srcset/tag.rb | require "RMagick"
require "digest/sha1"
module Jekyll
class SrcsetTag < Liquid::Tag
include Magick
attr_accessor :markup
def self.optipng?
@optinpng ||= system("which optipng")
end
def initialize(tag_name, markup, _)
@markup = markup
super
end
def render(context)
options = parse_options(markup, context)
return "Bad options to image_tag, syntax is: {% image_tag src=\"image.png\" width=\"100\"}" unless options["src"]
return "Error resizing - can't set both width and height" if options["width"] && options["height"]
site = context.registers[:site]
img_attrs = generate_image(site, options["src"], options)
srcset = []
(1..3).each do |factor|
srcset << {:factor => factor, :img => generate_image(site, options["src"], options.merge("factor" => factor))}
end
img_attrs["srcset"] = srcset.map {|i| "#{i[:img]["src"]} #{i[:factor]}x"}.join(", ")
"<img #{options.merge(img_attrs).map {|k,v| "#{k}=\"#{v}\""}.join(" ")}>"
end
def parse_options(markup, context)
options = {}
markup.scan(/(\w+)=((?:"[^"]+")|(?:'[^']+')|[\w\.\_-]+)/) do |key,value|
if (value[0..0] == "'" && value[-1..-1]) == "'" || (value[0..0] == '"' && value[-1..-1] == '"')
options[key] = value[1..-2]
else
options[key] = context[value]
end
end
options
end
def config(site)
site.config['srcset'] || {}
end
def optimize?(site)
config(site)['optipng']
end
def cache_dir(site)
config(site)['cache']
end
def generate_image(site, src, attrs)
cache = cache_dir(site)
sha = cache && Digest::SHA1.hexdigest(attrs.sort.inspect + File.read(File.join(site.source, src)) + (optimize?(site) ? "optimize" : ""))
if sha
if File.exists?(File.join(cache, sha))
img_attrs = JSON.parse(File.read(File.join(cache,sha,"json")))
filename = img_attrs["src"].sub(/^\//, '')
dest = File.join(site.dest, filename)
FileUtils.mkdir_p(File.dirname(dest))
FileUtils.cp(File.join(cache,sha,"img"), dest)
site.config['keep_files'] << filename unless site.config['keep_files'].include?(filename)
return img_attrs
end
end
img = Image.read(File.join(site.source, src)).first
img_attrs = {}
if attrs["height"]
scale = attrs["height"].to_f * (attrs["factor"] || 1) / img.rows.to_f
elsif attrs["width"]
scale = attrs["width"].to_f * (attrs["factor"] || 1) / img.columns.to_f
else
scale = attrs["factor"] || 1
end
img_attrs["height"] = attrs["height"] if attrs["height"]
img_attrs["width"] = attrs["width"] if attrs["width"]
img_attrs["src"] = src.sub(/(\.\w+)$/, "-#{img.columns}x#{img.rows}" + '\1')
filename = img_attrs["src"].sub(/^\//, '')
dest = File.join(site.dest, filename)
FileUtils.mkdir_p(File.dirname(dest))
unless File.exist?(dest)
img.scale!(scale) if scale <= 1
img.strip!
img.write(dest)
if dest.match(/\.png$/) && optimize?(site) && self.class.optipng?
`optipng #{dest}`
end
end
site.config['keep_files'] << filename unless site.config['keep_files'].include?(filename)
# Keep files around for incremental builds in Jekyll 3
site.regenerator.add(filename) if site.respond_to?(:regenerator)
if sha
FileUtils.mkdir_p(File.join(cache, sha))
FileUtils.cp(dest, File.join(cache, sha, "img"))
File.open(File.join(cache, sha, "json"), "w") do |f|
f.write(JSON.generate(img_attrs))
end
end
img_attrs
end
end
end
| ruby | MIT | ad7730dea2e3d4e03f8878e2b8fba8123cd06834 | 2026-01-04T17:45:46.319190Z | false |
netlify/jekyll-srcset | https://github.com/netlify/jekyll-srcset/blob/ad7730dea2e3d4e03f8878e2b8fba8123cd06834/lib/jekyll/srcset/version.rb | lib/jekyll/srcset/version.rb | module Jekyll
module Srcset
VERSION = "0.1.3"
end
end
| ruby | MIT | ad7730dea2e3d4e03f8878e2b8fba8123cd06834 | 2026-01-04T17:45:46.319190Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/run.rb | run.rb | require 'yaml'
require 'ynab'
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each { |f| require f }
Dir[File.join('.', 'lib/**/*.rb')].each { |f| require f }
# Gathering transactions
transactions =
Settings.all['accounts'].map do |a|
account = Account.new(a)
account.fetch_transactions
account.transactions
end.flatten!
# Importing transactions
budget_id = Settings.all['ynab'].fetch('budget_id')
access_token = Settings.all['ynab'].fetch('access_token')
ynab_api = YNAB::API.new(access_token)
begin
ynab_api.transactions.create_transaction(budget_id,
transactions: transactions)
rescue YNAB::ApiError => e
ErrorMessage.new(e).print
abort
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/spec/transaction_creator_spec.rb | spec/transaction_creator_spec.rb | RSpec.describe TransactionCreator do
VCR_OPTIONS = { match_requests_on: %i[method host path] }.freeze
describe '.call' do
subject(:call) do
described_class.call(
account_id: '123456789',
date: current_time,
payee_name: 'Payee',
payee_iban: 'IBAN',
category_name: nil,
category_id: nil,
memo: 'Very long memo exeeding 100 characters. 12345678991234567' \
'823456789234567893456789234567834567834567377777',
amount: 1.1,
is_withdrawal: false,
import_id: '12345678'
)
end
let!(:current_time) { Time.now }
it 'creates a YNAB transaction object' do
expect(call.instance_values).to eq(
'account_id' => '123456789',
'amount' => 1.1,
'category_id' => nil,
'cleared' => 'cleared',
'date' => current_time,
'flag_color' => nil,
'import_id' => '12345678',
'memo' => 'Very long memo exeeding 100 characters. 1234567899' \
'12345678234567892345678934567892345678345678345673',
'payee_id' => nil,
'payee_name' => 'Payee'
)
end
end
describe '.payee_id' do
subject(:method) { described_class.payee_id(options) }
let(:payee_id) { nil }
let(:options) { { payee_id: payee_id } }
context 'when payee_id is set' do
let(:payee_id) { '12345678' }
it 'returns that payee_id' do
expect(method).to eq(payee_id)
end
end
context 'when transaction is a withdrawal?' do
let(:expected_account_id) { 'ebec22d4-1905-11e8-8a4c-7b32b5a7e49f' }
before do
allow(described_class).to receive(:withdrawal?).and_return(true)
allow(described_class).to(
receive(:find_payee_id_by_account_id)
.and_return(expected_account_id)
)
end
it 'returns the payee_id of the cash account' do
expect(method).to eq(expected_account_id)
end
end
context 'when transaction is an internal transfer' do
before do
allow(described_class).to receive(:account_payee_id)
.and_return('12345')
end
it 'returns that payee_id' do
expect(method).to eq('12345')
end
end
context 'when nothing relevant is set' do
it 'returns nil' do
expect(method).to be_nil
end
end
end
describe '.account_payee_id' do
subject(:method) { described_class.account_payee_id(options) }
let(:options) { { payee_iban: payee_iban } }
context 'when the transfer is an internal transfer' do
let(:payee_iban) { 'DE89370400440532013000' }
let(:expected_account_id) { 'ebec22d4-1905-11e8-8a4c-7b32b5a7e49f' }
before do
allow(described_class).to(
receive(:find_payee_id_by_account_id)
.and_return(expected_account_id)
)
end
it 'returns the correct account id' do
expect(method).to eq(expected_account_id)
end
end
context 'when the transfer is NO internal transfer' do
let(:payee_iban) { nil }
it 'returns the correct account id' do
expect(method).to be_nil
end
end
end
describe '.find_payee_id_by_account_id', vcr: VCR_OPTIONS do
subject(:method) do
described_class.find_payee_id_by_account_id(account_id)
end
let(:account_id) { 'ebec22d4-1905-11e8-8a4c-7b32b5a7e49f' }
it 'returns the correct account id' do
expect(method).to eq('57244b6e-c35e-11e8-8178-8f80c501f13b')
end
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/spec/spec_helper.rb | spec/spec_helper.rb | require 'vcr'
ENV['ENV'] = 'test'
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each { |f| require f }
Dir[File.join('.', 'lib/**/*.rb')].each { |f| require f }
VCR.configure do |config|
config.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
config.hook_into :webmock
config.configure_rspec_metadata!
config.default_cassette_options = { record: :none }
end
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/spec/dumper/n26_spec.rb | spec/dumper/n26_spec.rb | vcr_options = { cassette_name: 'dumper/n26',
record: :none,
match_requests_on: %i[method host path] }
RSpec.describe Dumper::N26, vcr: vcr_options do
subject(:object) { Dumper::N26.new(params) }
let(:skip_pending_transactions) { false }
let(:params) do
{
'ynab_id' => '123466',
'username' => 'username',
'password' => 'password',
'iban' => 'DE89370400440532013000',
'skip_pending_transactions' => skip_pending_transactions
}
end
let(:transaction_pending) do
JSON.parse(File.read('spec/fixtures/dumper/n26/transaction_pending.json'))
end
let(:transaction_processed) do
JSON.parse(File.read('spec/fixtures/dumper/n26/transaction_processed.json'))
end
let(:transactions) do
client = TwentySix::Core.authenticate('username', 'password')
client.transactions
end
describe '#fetch_transactions' do
subject(:method) { object.fetch_transactions }
before do
allow(TransactionCreator).to(
receive(:find_payee_id_by_account_id)
.and_return('12345')
)
end
it 'sets the transactions' do
expect(method).to be_truthy
end
it 'has the correct transaction amount' do
expect(method.size).to eq(4)
end
end
# describe '#category_name' do
# let(:method) { object.send(:category_name, transactions[2]) }
# before do
# categories = ['micro-v2-food-groceries' => 'Food']
# allow(object).to receive(:@categories).and_return(categories)
# end
# context 'when set_category is set to true' do
# let(:params) do
# {
# 'ynab_id' => '123466',
# 'username' => 'username',
# 'password' => 'password',
# 'iban' => 'DE89370400440532013000',
# 'set_category' => true
# }
# end
# it 'returns the N26 category name' do
# expect(method).to eq('Food & Groceries')
# end
# end
# context 'when set_category is set to false' do
# it 'returns nil' do
# expect(method).to eq(nil)
# end
# end
# end
describe '#memo' do
let(:method) { object.send(:memo, transaction) }
context 'when reference text and city are present' do
let(:transaction) { transactions.last }
it 'merges reference text and city name' do
expect(method).to eq('Bargeldabhebung BARCELONA')
end
end
context 'when only city name is present' do
let(:transaction) { transactions[2] }
it 'returns the city name' do
expect(method).to eq('BARCELONA')
end
end
context 'when only reference text is present' do
let(:transaction) { transactions[1] }
it 'returns the reference text' do
expect(method).to eq('Test fuer eine Api')
end
end
end
describe '#amount' do
let(:method) { object.send(:amount, transaction) }
context 'when amount is below 1 euro' do
let(:transaction) { transactions.first }
it 'converts it correctly to an integer' do
expect(method).to eq(-10)
end
end
context 'when amount is below 10 euros' do
let(:transaction) { transactions[2] }
it 'converts it correctly to an integer' do
expect(method).to eq(5440)
end
end
context 'when amount is greater than 100 euros' do
let(:transaction) { transactions[3] }
it 'converts it correctly to an integer' do
expect(method).to eq(-500_000)
end
end
end
describe '#withdrawal?' do
let(:method) { object.send(:withdrawal?, transaction) }
context 'when transaction is withdrawal' do
let(:transaction) { transactions.last }
it 'returns true' do
expect(method).to be_truthy
end
end
context 'when transaction is not a withdrawal' do
let(:transaction) { transactions.first }
it 'returns true' do
expect(method).to be_falsy
end
end
end
describe '#import_id' do
let(:method) { object.send(:import_id, transactions.first) }
it 'sets it correctly' do
expect(method).to eq('46c9ccde424652bc013dca9b408dcdec')
end
end
describe '.accept?' do
subject(:accept?) { object.accept?(transaction) }
context 'when skip_pending_transactions feature is disabled' do
context 'when the transaction is pending' do
let(:transaction) { transaction_pending }
it 'returns true' do
expect(accept?).to be_truthy
end
end
context 'when the transaction is processed' do
let(:transaction) { transaction_processed }
it 'returns true' do
expect(accept?).to be_truthy
end
end
end
context 'when skip_pending_transactions feature is disabled' do
let(:skip_pending_transactions) { true }
context 'when the transaction is pending' do
let(:transaction) { transaction_pending }
it 'returns false' do
expect(accept?).to be_falsy
end
end
context 'when the transaction is processed' do
let(:transaction) { transaction_processed }
it 'returns true' do
expect(accept?).to be_truthy
end
end
end
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/lib/error_message.rb | lib/error_message.rb | # Used to print out friendly error messages that help the user
# understand what went wrong and how to solve it
class ErrorMessage
require 'colorize'
def initialize(e)
@e = e
end
def print
puts summary
puts heading('Returned error message:')
puts message
puts heading('What you can do about the error:')
puts action
end
private
def summary
"⚠️ YNAB API Error: #{@e.name} (#{@e.id})".colorize(color: :red,
background: :default)
end
def heading(text)
[
"\n\n\n",
text.colorize(color: :red, background: :default).underline,
"\n\n"
].join
end
def message
pretty_json || @e.detail
end
def pretty_json
JSON.pretty_generate(JSON.parse(@e.detail))
rescue JSON::ParserError => _e
false
end
def action
if @e.name == 'unauthorized'
puts '→ Please check your credentials, they seem to be incorrect.'
elsif @e.id == 404
puts '→ Double-check that the your configured `budget_id` and' \
'`ynab_id` for each dumper are correct.'
else
puts '→ Please consider reading the error message above to find out more.'
end
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/lib/account.rb | lib/account.rb | # Represents a real bank account but maps it with a YNAB account
# Uses the correct dumper to fetch the transactions.
class Account
attr_accessor :dumper, :iban, :ynab_id, :transactions
def initialize(params = {})
@dumper = Dumper.get_dumper(params.fetch('dumper'))
@iban = normalize_iban(params.fetch('iban'))
@ynab_id = params.fetch('ynab_id')
params['iban'] = @iban # overwrite with normalized iban
@params = params
@transactions = nil
end
def fetch_transactions
dumper = @dumper.new(@params)
@transactions = dumper.fetch_transactions.compact
end
private
def normalize_iban(iban)
iban.delete(' ')
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/lib/settings.rb | lib/settings.rb | # Reads the settings from the yaml file
class Settings
def self.all
@settings ||= begin
if ENV['ENV'] == 'test'
YAML.load_file(File.join('.', 'spec/config.test.yml'))
else
YAML.load_file(File.join('.', 'config.yml'))
end
end
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
gitviola/ynab-bank-importer | https://github.com/gitviola/ynab-bank-importer/blob/d69e289b8136861c4504f50d68843e9abab5bf1e/lib/dumper.rb | lib/dumper.rb | # Uses methods that need to be implemented by each dumper -
# this is to enforce consitency.
class Dumper
def self.get_dumper(name)
case name
when :bbva
Dumper::Bbva
when :n26
Dumper::N26
when :fints
Dumper::Fints
else
raise "Dumper \"#{name}\" not supported."
end
end
# rubocop:disable Metrics/MethodLength
def to_ynab_transaction(transaction)
return nil if date(transaction).nil? || date(transaction) > Date.today
::TransactionCreator.call(
account_id: account_id,
date: date(transaction),
payee_name: payee_name(transaction),
payee_iban: payee_iban(transaction),
category_name: category_name(transaction),
category_id: category_id(transaction),
memo: memo(transaction),
amount: amount(transaction),
is_withdrawal: withdrawal?(transaction),
import_id: import_id(transaction)
)
end
# rubocop:enable Metrics/MethodLength
def category_name(_transaction)
nil
end
def category_id(_transaction)
nil
end
def normalize_iban(iban)
iban.delete(' ')
end
end
| ruby | MIT | d69e289b8136861c4504f50d68843e9abab5bf1e | 2026-01-04T17:45:50.785060Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.